-1

I am receiving times in the an AJAX request and am converting them using the new Date() function.

I receive 2013-06-18T12:00:15Z

However, somehow I get the following after new Date():

Tue Jun 18 2013 08:00:15 GMT-0400 (EDT)

Why is it not:

Tue Jun 18 2013 12:00

See the following demo:

http://www.w3schools.com/js/tryit.asp?filename=tryjs_date_convert

Outshined
  • 1
  • 2

2 Answers2

2

This is a time zone problem. You must be in the EDT timezone (GMT-0400). To correctly parse the date you should tell the parser in which timezone your date is correct.

For you parse your date like this : new Date('2013-06-18 12:00:15 GMT-0400')

"GMT-0400" means GMT time minus 4 hours

Or if you don't wish to reformat your string, you can use the date.getUTC* functions to get the time as you parsed it.

The full list is available at Mozilla's documentation.

Vadim Caen
  • 1,526
  • 11
  • 21
0

I agree with Vaim Caen's answer that this is a timezone issue, but not with parsing - the date is being parsed fine, but into your local timezone, while you're expecting it to be parsed into UTC date.

This answer shows how to convert from your current timezone to UTC - applying this to the TryIt demo gives:

var msec = Date.parse("2013-06-18T12:00:15Z");
// or: var msec = Date.parse("Tue Jun 18 2013 08:00:15 GMT-0400 (EDT)");
var d = new Date(msec);
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
document.getElementById("demo").innerHTML = d;

Edit: If you all you're interested in is displaying the date (no further manipulations) then you can use:

d.toUTCString()

which will show the date in GMT (for me it actually shows "GMT" so most likely not of use!)

The alternative is to add a function to the prototype to show the date in whatever format you want and use the date.getUTC* methods.

Community
  • 1
  • 1
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • The date is being parsed as a GMT date. This is the normal behaviour with the "dateTtimeZ" format. But it is displayed in the local time zone format. – Vadim Caen Aug 25 '15 at 22:39
  • Interesting - how do you determine this? If this was the case commands like `.getHours()` would give the UTC hours, not local timezone. Given that the `.toUTCx()` methods were *added* in JavaScript 1.3, I would conclude that it parses/stores it with local timezone, not UTC (or GMT). TBH however it stores it internally is irrelevant if all the commands give the timezone version. – freedomn-m Aug 25 '15 at 22:46
  • In the parse() [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) it is stated that : _The UTC time zone is used to interpret arguments in ISO 8601 format that do not contain time zone information_ (and GMT and UTC are the same) – Vadim Caen Aug 26 '15 at 07:16
  • Ah, I misinterpreted your comment - to reword/summarise: When no timezone is present on the input, it is parsed *as* GMT, *into* your local timezone. – freedomn-m Aug 26 '15 at 10:05