Fibericon
Fibericon

Reputation: 5793

IE9 Date object handling

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?

Upvotes: 0

Views: 319

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161457

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.

Upvotes: 1

RobG
RobG

Reputation: 147363

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.

Upvotes: 1

Related Questions