Moment Timezone not returning expected result - javascript

I might be doing something silly here. But essentially, the time in Lisbon right now is 12:27 PM
but the following returns 14:27 (EU central time)
const time = moment.tz("Europe/Lisbon")
const timeZone = "Europe/Lisbon"
const format = "'HH[:]mm'"
const startMoment = moment.tz(item.startTime, format, timeZone);
const endMoment = moment(item.endTime, format, timeZone);
return time.isBetween(startMoment, endMoment);
I tried several combinations and I get the wrong answer everytime. For example if I set timeZone to be "Europe/Warsaw" it returns 15:27 whereas it should be 13:27.
EDIT: const currentTime = moment().tz("Europe/London").format() returns the correct time for London. However, the return statement moment(currentTime).isBetween(startMoment, endMoment) still reads "moment(correntTime)" as the local time.

isBetween return boolean . And isBetween runs on date object. You are trying to run on time zone object. which is different from date object
const time = moment.tz("Europe/Lisbon")
const timeZone = "Europe/Lisbon"
const format = "'HH[:]mm'"
const startMoment = moment().subtract(8, 'months').tz(timeZone).format();
const endMoment = moment(new Date()).tz(timeZone).format() ;
console.log("startMoment",startMoment)
console.log("endMoment",endMoment)
console.log(moment.tz(new Date(),"Europe/Lisbon").format())
console.log(moment('2020-09-30').isBetween(startMoment, endMoment));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

Related

Check if an iso string date is same or before an hour using moment

I've a string date in ISO format and a string in format HH:mm.
I want to know if the hour of the string ISO date is same or before the string in format HH:mm.
Example:
const isoDateString = '2021-09-28T07:30:00Z' // UTC
const hour = '07:30' // not UTC
-> result true
---
const isoDateString = '2021-09-28T07:30:00Z' // UTC
const hour = '08:30' // not UTC
-> result false
I'm using moment and this is my code:
const TIME_FORMAT = 'HH:mm'
const isoDateString = '2021-09-28T09:30:00Z'
const hour = '07:30'
const isHourSameOrBeforeIsoString = moment(
moment(isoDateString).format(TIME_FORMAT),
).isSameOrBefore(moment(hour, TIME_FORMAT));
console.log(isHourSameOrBeforeIsoString)
It doesn't work. It returns false in both cases. Why?
Use moment.utc() when constructing your iso date string because you should handle that as in UTC.
I also added TIME_FORMAT inside moment constructor of formatted iso date string.
const TIME_FORMAT = 'HH:mm'
const isoDateString = '2021-09-28T09:30:00Z'
const hour = '07:30'
const isHourSameOrBeforeIsoString = moment(
moment.utc(isoDateString).format(TIME_FORMAT), TIME_FORMAT
).isSameOrBefore(moment(hour, TIME_FORMAT));
console.log(isHourSameOrBeforeIsoString)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Here is a more reasonable way to check in my opinion:
The logic you had was correct, but the reason it is returning false is because your isoDateString is returning 8:30 and the hour you are comparing it to is 7:30, like Krzysztof mentioned in their comment, it could be a time zone issue:
var format = 'hh:mm'
// var time = moment() gives you current time. no format required.
var time = moment('2021-09-28T09:30:00Z',format),
testTime = moment('07:30', format);
console.log(moment(time).format(format));
console.log(moment(testTime).format(format));
if (time.isSameOrBefore(testTime)) {
console.log('is before')
}
if(time.isSameOrAfter(testTime)){
console.log('is after')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" referrerpolicy="no-referrer"></script>

get today's date with parsed time in moment

I am trying to get the today's date with the time which I specified using moment js. My attempt is as below.
const time = '18:00'
const timeAndDate = moment(time)
But when I print timeAndDate it says invalid date. Is there any other way to achieve this?
const minute = 0
const hour = 18
const timeAndDate = moment().hours(hour).minutes(minute);
https://momentjs.com/docs/#/get-set/hour/
It's enough to specify the time format like second parameter in moment
const timeOfToday = moment('18:00', 'HH:mm');
console.log(timeOfToday);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

How can I get the ISO format for date and time in javascript?

I have two separate fields of date and time:-
const date = 2020-12-10;
const time = 22:00;
expected output:-
2020-12-10T10:00:00Z
I'm following this approach but the time in coming wrong:-
const date = DateUtil.getFullDateString(this.state.date_value);
const time = moment(this.state.time_value, ['HH.mm']).format('hh:mm a');
const momentObj = moment(date + time, 'YYYY-MM-DD HH:mm');
const dateTime = momentObj.toISOString();
the output of time is coming 18:30:00 but need to have 10:00:00
2020-12-10T18:30:00Z
You could parse date and time one by one, then add time to date and finally format as you want.
const date = '2020-12-10';
const time = '22:00';
const momentDate = moment(date).utc().startOf('day'); // utc() to avoid the offset
console.log(momentDate);
const momentTime = moment(time, 'HHmm').format('HH:mm');
console.log(momentTime);
const resultTime = momentDate.add(momentTime);
console.log(resultTime);
// Format as you want
console.log(resultTime.format('LLL'));
console.log(resultTime.format('YYYY-MM-DDThh:mm:ss.SSSA[Z]'));
console.log(resultTime.toISOString());
<script src="https://momentjs.com/downloads/moment.js"></script>
See this in order to know how to manage the UTC offset.

How to convert a a type number in format 2300 to hours and compare to current time with Moment.js?

Given a number 1500 which is supposed to represent the time 15:00 (3pm). I'd like to convert it to a moment time and be able to compare it to the current time.
How to make this conversion and how to get the current time in that same format to be able to compare it?
const now = moment();
const time = moment('1500', 'hhmm');
const diff = moment.duration(now.diff(time));
Then to compare you can use
diff.minutes(), diff.seconds(), or diff.hours()
https://momentjs.com/docs/#/displaying/difference/
You can get the current date: moment();
Then you can set the hours and minutes: moment().set("hour", numberString.substring(0, 2)).set("minute", numberString.substring(2, 4));
Altogether that'd be:
const numberString = "1500";
const now = moment();
const nowAtNumberStringTime = moment().set("hour", numberString.substring(0, 2)).set("minute", numberString.substring(2, 4));
const difference = now.diff(nowAtNumberStringTime);
console.log(difference);

Moment Js UTC to Local Time

I'm trying to convert UTC time to the local time. I've been following this example from this link: http://jsfiddle.net/FLhpq/4/light/. I can't seem to get the right local output. For example, if its 10: 30 am in here, instead of getting 10:30 ill get 15: 30. Here is my code:
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
var localTime = moment.utc(date).toDate();
localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
console.log("moment: " + localTime);
No matter what I do the time always comes out at UTC time. I live in Houston so I know timezone is the issue. I've followed the code in the link but can seem to get the local time. What am I doing wrong?
To convert UTC time to Local you have to use moment.local().
For more info see docs
Example:
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
console.log(date); // 2015-09-13 03:39:27
var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');
console.log(local); // 2015-09-13 09:39:27
Demo:
var date = moment.utc().format();
console.log(date, "- now in UTC");
var local = moment.utc(date).local().format();
console.log(local, "- UTC now to local");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Try this:
let utcTime = "2017-02-02 08:00:13";
var local_date= moment.utc(utcTime).local().format('YYYY-MM-DD HH:mm:ss');
let utcTime = "2017-02-02 08:00:13.567";
var offset = moment().utcOffset();
var localText = moment.utc(utcTime).utcOffset(offset).format("L LT");
Try this JsFiddle
To convert UTC to local time
let UTC = moment.utc()
let local = moment(UTC).local()
Or you want directly get the local time
let local = moment()
var UTC = moment.utc()
console.log(UTC.format()); // UTC time
var cLocal = UTC.local()
console.log(cLocal.format()); // Convert UTC time
var local = moment();
console.log(local.format()); // Local time
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Note: please update the date format accordingly.
Format Date
__formatDate: function(myDate){
var ts = moment.utc(myDate);
return ts.local().format('D-MMM-Y');
}
Format Time
__formatTime: function(myDate){
var ts = moment.utc(myDate);
return ts.local().format('HH:mm');
},
This is old question I see, but I didn't really get what I was looking for. I had a UTC datetime which was formatted without timezone. So I had to do this:
let utcDatetime = '2021-05-31 10:20:00';
let localDatetime = moment(utcDatetime + '+00:00').local().format('YYYY-MM-DD HH:mm:ss');
I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!
Full Example on Codesandbox (DEMO):
https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js
This is what worked for me, it required moment-tz as well as moment though.
const guess = moment.utc(date).tz(moment.tz.guess());
const correctTimezone = guess.format()
Here is what I do using Intl api:
let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney
this will return a time zone name. Pass this parameter to the following function to get the time
let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});
let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});
you can also format the time with moment like this:
moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');
I've created one function which converts all the timezones into local time.
Requirements:
1. npm i moment-timezone
function utcToLocal(utcdateTime, tz) {
var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
var localDateTime
var hours = zoneValue.split(":")[0]
var minutes = zoneValue.split(":")[1]
if (operator === "-") {
localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else if (operator) {
localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else {
localDateTime = "Invalid Timezone Operator"
}
return localDateTime
}
utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")
//Returns "2019-11-14 12:45:37"

Categories