0

I have the following line, which generates a valid timestamp in FF and Chrome:

new Date('2012 11 2 00:00:00 GMT').getTime();

However, in IE9, I get NaN. What needs to be done differently to get this line to be cross browser compatible?

Fibericon
  • 5,684
  • 12
  • 37
  • 64
  • possible duplicate of [How can I convert string to datetime with format specification in JavaScript?](http://stackoverflow.com/questions/476105/how-can-i-convert-string-to-datetime-with-format-specification-in-javascript) – Peter O. Nov 02 '12 at 04:13

2 Answers2

1

The date format you are using should conform to the EMCAscript spec, it just so happens that Firefox and Chrome are more forgiving about parsing.

The format should be:

YYYY-MM-DDTHH:mm:ss.sssZ

So try this:

new Date('2012-11-02T00:00:00.000Z').getTime()

This will not work in older versions of IE. If you need full compatability then refer to the other answer.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • MDN is not an authority, [ECMA-262](http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15) is. Not all browsers support the ISO format specified, and those that do are inconsistent. Much better to manually parse date strings. – RobG Nov 02 '12 at 04:22
  • The ISO format fails in older versions of IE. Manually parsing dates is the only way to get consistent results in a wide range of browsers in use. – RobG Nov 02 '12 at 05:09
  • @RobG True, but he said IE9 in the question. I'll add a note for clarity though. – loganfsmyth Nov 02 '12 at 05:12
1

The only reliable way to convert a string to a date is to parse it manually. You can use a library, but whatever you use you must know the format so it's usually simpler to just do it yourself.

In the case of '2012 11 2 00:00:00 GMT' (which is not compliant with ISO8601 and therefore parsing is implementation dependent), if the timezone is always UTC, you can use:

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

The resulting date object will have a timezone offset based on the client's system setting, which should be correct, but may not be.

RobG
  • 142,382
  • 31
  • 172
  • 209