简体   繁体   English

IE9 Date对象处理

[英]IE9 Date object handling

I have the following line, which generates a valid timestamp in FF and Chrome: 我有以下行,它在FF和Chrome中生成有效的时间戳:

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

However, in IE9, I get NaN. 但是,在IE9中,我得到了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. 您使用的日期格式应符合EMCAscript规范,只需要Firefox和Chrome对解析更加宽容。

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. 这在旧版本的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: 在'2012 11 2 00:00:00 GMT'的情况下(不符合ISO8601,因此解析依赖于实现),如果时区始终是UTC,您可以使用:

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. 生成的日期对象将根据客户端的系统设置具有时区偏移量,该设置应该是正确的,但可能不是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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