Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript equlivent to .Net TimeZoneInfo.ConvertTimeBySystemTimeZoneId

In .Net I can use the following to figure out what time it is in a specified timezone:

var targetDate = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, "Atlantic Standard Time");

I've been trying to figure out a way to do this in Javascript, but so far no luck. I was able to find the following: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/ which has some details, if I can specify an offset, but I cant seem to figure out how to get that from a specified timezone (from the currentTimezone its as easy as myDate.getTimezoneOffset()).

Again in .Net I could do this with:

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Atlantic Standard Time");
TimeSpan offset = tzi.GetUtcOffset( myDateTime);
like image 546
Kyle Avatar asked Oct 21 '13 13:10

Kyle


1 Answers

JavaScript can't do this natively. You'll need a library. I provided a list of several different libraries for this here.

Also recognize that "Atlantic Standard Time" is a Microsoft time zone identifier. You need to use the equivalent IANA time zone, which would be "America/Halifax". You can read more in the timezone tag wiki, under "Time Zone Databases". If you need to convert from Microsoft identifiers, you'll have to do that in your .NET code, using Noda Time, as I described here.

Here is an example of using moment-timezone:

(intentionally split into separate statements for readability)

var now = moment();
var atlantic = now.tz("America/Halifax");
var s = atlantic.format();
like image 80
Matt Johnson-Pint Avatar answered Sep 21 '22 21:09

Matt Johnson-Pint