Moment.Js: Offsetting dates using UTC and Timezone offset
42,417
Solution 1
Here is what worked for me:
var date = {
utc: '2013-10-16T21:31:51',
offset: 480
}
var returnDate = moment.utc(date.utc).zone(date.offset).format('MM/DD/YYYY h:mm A');
If you noticed, I changed the offset to a positive number. This gave the desired result. If the offset was left at -480
the output was 10/17/2013 5:31 AM
.
There is a moment#UTC method that initializes the date as UTC vs. local time.
Solution 2
I use the jsTimezoneDetect library to determine the timezone name instead of the offset.
Then use this on a UTC timestamp:
timestamp = moment.tz(timestamp, tz.name());
timestamp.format('MM/DD/YYYY h:mm A');
Related videos on Youtube
Comments
-
Neil almost 2 years
I am trying to adjust a time using a timezone offset and a UTC timestamp.
I am running the following code:
var date = { utc: '2013-10-16T21:31:51', offset: -480 } var returnDate = moment(date.utc).utc().zone(date.offset).format('MM/DD/YYYY h:mm A');
What I am expecting is:
10/16/2013 1:31 PM
but I am ending up with10/17/2013 9:31 AM
-
Neil Kistner over 10 yearsWhat does the date look like if you remove the
.utc().zone(date.offset)
? So that way you call just.format()
on it. -
Neil Kistner over 10 yearsAlso, if looking at the documentation here and scroll down a little bit. It reads, "Unless you specify a timezone offset, parsing a string will create a date in the current timezone."
-
Neil over 10 yearsI've posted bad data, let me correct this. sec
-
Neil over 10 yearsIt looks like this: 10/16/2013 9:31 PM with
moment(date.utc).format('MM/DD/YYYY h:mm A');
-
Neil Kistner over 10 yearsWhat is the current timezone of the server this is running on? If it is not in UTC, you are passing in a UTC date already, and then calling
.utc()
on it, which is further advancing the time. -
Neil over 10 yearsI'm unsure of the server time, these dates are coming from a database of events, when they occur. When I use
moment(date.utc).zone(date.zone).format('MM/DD/YYYY h:mm A');
I end up with10/17/2013 9:31 AM
again -
Jason Sperske over 10 yearsI think if you are going to be adjusting for timezone then you will have to become sure of the server timezone because moment.js is parsing the date from the users browser.
-
-
potench almost 10 yearsFor other's stumbling on this post, you can use a string for the
offset
that's perhaps more legible:zone('-07:00')
(PST example) -
godimedia almost 9 years
moment.zone()
is deprecated after moment 2.9.0 -
medBouzid almost 9 yearsthe method zone() is deprecated, everyone should use utcOffset() instead see here github.com/moment/moment/issues/1779