Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.Js: Offsetting dates using UTC and Timezone offset

Tags:

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 with 10/17/2013 9:31 AM

like image 917
Neil Avatar asked Jan 15 '14 17:01

Neil


People also ask

How do I get timezone from UTC offset?

Timezone offset is the time difference in hours or minutes between the Coordinated Universal Time (UTC) and a given time zone. The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time.

How do you use moments in UTC?

utc() will be in UTC mode, and any moment created with moment() will not. To switch from UTC to local time, you can use moment#utc or moment#local.

How do you use moments with time zones?

To use moment-timezone, you will need [email protected]+ , moment-timezone. js , and the moment-timezone data. For convenience, there are builds available on momentjs.com/timezone/ with all the zone data or a subset of the data. moment-timezone-with-data.


2 Answers

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.

like image 121
Neil Kistner Avatar answered Sep 23 '22 20:09

Neil Kistner


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'); 
like image 40
Asa Carter Avatar answered Sep 20 '22 20:09

Asa Carter