Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have a UTC string and I want to convert it to UTC Date Object in JavaScript [duplicate]

Tags:

javascript

I am using JavaScript, I have a JSON call that returns my UTC DateTimes as strings and I want to convert them to UTC Date objects. Has anyone done this? I do not want to go to local time at all.

like image 512
seroth Avatar asked Nov 23 '16 15:11

seroth


1 Answers

On any vaguely-modern browser, you just pass that into Date with a "Z" on the end:

var dt = new Date(yourString + "Z");

That format was defined for JavaScript in the ES5 specification in December 2009. The "Z" is important to ensure that the string is interpreted as UTC, not local time¹.

Date objects keep track of a specific instant in time, which is irrespective of timezone. If you use the Date's UTC methods (getUTCFullYear, getUTCMonths, etc.), you'll access that instant in UTC. (If you use the non-UTC methods, you'll access it translated to local time.)

Example:

var str = "2016-11-22T17:14:00";
var dt = new Date(str + "Z");
console.log("UTC string:");
console.log(dt.toUTCString());
console.log("Local string");
console.log(dt.toString());
console.log("Hours UTC:   " + dt.getUTCHours());
console.log("Hours local: " + dt.getHours());

¹ There's a bit of history in regard to that. When the format was originally added to the ES5 specification, it was supposed to be a subset of ISO-8601, but the ES5 spec said that no timezone indicator meant UTC, whereas in ISO-8601, no timezone indicator means local time. That lead to inconsistent implementations, where some were true to the ES5 specification, and others were true to ISO-8601. The bug was fixed in the ES2015 specification in June 2015. Now JavaScript's date/time format really is a subset of ISO-8601, except that JavaScript's Date always has a time component (all the way down to milliseconds), while ISO-8601 has the concept that a value may only be as specific as it is precise. That is, 2016-11-22 in JavaScript is a specific date and time, but in ISO-8601, it's just the date (no time is implied). Consequently, the current (ES2016) JavaScript specification says:

When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.

So 2016-11-22 is interpreted as 2016-11-22 at midnight UTC, but 2016-11-22T00:00:00 is interpreted as 2016-11-22 at midnight local time. Bizarre, but true. Of course, this latest language in the specification may not be correctly implemented by all implementations yet (I note that Chrome 54 gets it wrong, for instance).

Bottom line: You need that "Z" to ensure the string is parsed as UTC.

like image 156
T.J. Crowder Avatar answered Sep 29 '22 14:09

T.J. Crowder