简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM