user1561753
user1561753

Reputation: 357

Javascript newDate(datestring) seems to be changing my time zone

So I have a datestring that looks like

2014-08-02T19:00:00

Which should come out to Aug 02 2014 7PM (EST) but when I create a date object it seems to change it to

Sat Aug 02 2014 15:00:00 GMT-0400 (Eastern Daylight Time)

Basically it seems to be assuming that the datestring was in GMT-0000. Is there a way for me to tell it the GMT of the datestring so it doesn't automatically adjust it?

Upvotes: 0

Views: 41

Answers (2)

RobG
RobG

Reputation: 147563

Do not use the Date constructor to parse strings (it uses Date.parse).

An ISO 8601 format string with not timezone will be parsed as UTC by some browsers (e.g. Firefox per ES5) and local by others (e.g. Chrome per the ES 6 draft) and fail completely in yet others to return NaN (e.g. IE 8). Parse the string yourself so that it is always one or the other.

The following will parse it as UTC:

function parseISOUTC(s) {
  var b = s.split(/\D+/);
  return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5]));
}

console.log(parseISOUTC('2014-08-02T19:00:00').toISOString()); // 2014-08-02T19:00:00.000Z

Given the change in specification between ES5 and the edition 6 draft, event parsing the one format specified by ECMA-262 in the very latest browsers will remain problematic for some time.

Upvotes: 0

Bart
Bart

Reputation: 27245

That's because your datestring is in GMT.

If your datestring actually is in EST, it should look like this:

2014-08-02T19:00:00-04:00

Specification: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

Upvotes: 3

Related Questions