Date.getTime()在IE11中返回ISO / Twitter API日期的NaN

时间:2015-02-05 11:43:38

标签: javascript internet-explorer date timestamp

这是my code

var date = "2014-07-23T15:23:12+0000";
var ts = new Date(date).getTime();
console.log(ts);

为什么IE11会打印NaN

Firefox / Chrome /和其他浏览器在打印1406128992000时没有问题。

1 个答案:

答案 0 :(得分:4)

引自ECMAScript语言规范,第Date Time String Format部分:

  

ECMAScript定义了基于日期时间的字符串交换格式   简化了ISO 8601扩展格式。格式是   如下:YYYY-MM-DDTHH:mm:ss.sssZ
  ...
  Z是指定为" Z"的时区偏移量。 (对于UTC)或者" +"或" - "然后是时间表达式HH:mm

显然,您需要在时区指示符中添加:。这应该适用于IE9:



var dateString = "2014-07-23T15:23:12+0000";
var dateStringISO = dateString.replace(/([+\-]\d\d)(\d\d)$/, "$1:$2");
var timestamp = new Date(dateStringISO).getTime();
console.log(dateString, dateStringISO, timestamp);




对于Twitter日期,您可以使用相同的策略:



var dateString = "Mon Jan 13 16:04:04 +0000 2014";
var dateStringISO = dateString.replace(/^... (...) (..) (........) (...)(..) (....)$/, function(match, month, date, time, tz1, tz2, year) {
  return year + "-" + {
    Jan: "01",
    Feb: "02",
    Mar: "03",
    Apr: "04",
    May: "05",
    Jun: "06",
    Jul: "07",
    Aug: "08",
    Sep: "09",
    Oct: "10",
    Nov: "11",
    Dec: "12"
  }[month] + "-" + date + "T" + time + tz1 + ":" + tz2;
});
var timestamp = new Date(dateStringISO).getTime();
console.log(dateString, dateStringISO, timestamp);