6
votes

I see an excellent summary of handling time in webapp here. But, it doesn't clearly address the below scenario. I wanted a way to get the local time in web application based on date time at UTC + Location(iana timezone location - America/New_York).

I am looking for a library which does the following calculation. If it works natively in Javascript, that also suit my purpose.

From server, following information is retrieved

{
  dateTime: "2002-10-27T15:04:05Z" # Time in UTC, no TimeZone info
  userTimeZone: "America/New_York" # based on current user location
}

The issue is that, I couldn't find a way to convert it to the time at location (New York) considering daylight savings offset.

I am not sure saving time zone offset in database solve the issue as my user may be from across region and may look at the same data. For example, the event happened at a location belongs to Estern zone (EST/EDT), but the user at Pacific zone may query the data based on their location (8AM - 5PM "America/Los_Angeles" - PST/PDT).

I looked at Moment.js, but couldn't find a solution.

To summarize, I need a way to get the local time at a specific location(considering daylight savings offset) in web browser, from an input of date time at UTC + IANA location.

3
Hi, what did you choose at the end?Maziyar

3 Answers

5
votes

Original Answer

MomentJS is an excellent library, but it is focused on parsing. You need TimezoneJS, which implements the Olson database in javascript.

Your use case is one of the first described in the documentation.

Updated Answer

There are multiple libraries for doing time zone conversions in JavaScript, as listed here. At the time this question was originally asked, I was only aware of TimezoneJS.

Since you asked about moment.js, you should use the moment-timezone plugin. (This wasn't available when you originally asked the question.)

var x = // your object as written in the question

var m = moment(x.dateTime).tz(x.userTimeZone);

var s = m.format(); // or whatever you want to do
4
votes

You can achieve this without a library using the toLocaleDateString method:

// prints 'Sun, Oct 27, 2002, 10:04 AM EST'
new Date('2002-10-27T15:04:05Z')
.toLocaleDateString('en-US', {
  timeZone:'America/New_York',
  timeZoneName: 'short',
  minute: 'numeric',
  hour: 'numeric',
  weekday: 'short',
  day: 'numeric',
  year: 'numeric',
  month: 'short',
});

Intl.DateTimeFormat works in a very similar fashion.

Tested on Chrome, Firefox and Safari (OSX). Note that according to MDN, the timezone property only needs to support 'UTC' and the full IANA database may not be implemented in all browsers. Feel free to update this answer with support across other setups.

2
votes

The fine folks at MomentJS have created another library called Moment Timezone. I think this is exactly what you're looking for. Specifically:

var zone = moment.tz.zone('America/New_York');
zone.parse(Date.UTC(2012, 2, 19, 8, 30)); // 240