最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Date.getTime() returns NaN for ISOTwitter API dates in IE11 - Stack Overflow

programmeradmin8浏览0评论

This is my code:

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

Why does IE11 print NaN?

Firefox/Chrome/and other browsers have no problems on printing 1406128992000.

This is my code:

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

Why does IE11 print NaN?

Firefox/Chrome/and other browsers have no problems on printing 1406128992000.

Share Improve this question edited Feb 5, 2015 at 16:04 Salman Arshad 273k84 gold badges444 silver badges534 bronze badges asked Feb 5, 2015 at 11:43 markzzzmarkzzz 48.1k126 gold badges319 silver badges534 bronze badges 5
  • I'm guessing the date string is invalid, and getTime from invalid date is NaN – adeneo Commented Feb 5, 2015 at 11:44
  • Safari returns NaN too. – pavel Commented Feb 5, 2015 at 11:45
  • Your problem is right here 2014-07-23T15:23:12+0000 – Lewis Commented Feb 5, 2015 at 11:45
  • I don't have controls of that data. It bees from social api/json. How could I do? – markzzz Commented Feb 5, 2015 at 11:47
  • You should be parsing the date somehow, and pass numbers to the Date constructor. – adeneo Commented Feb 5, 2015 at 11:48
Add a ment  | 

1 Answer 1

Reset to default 6

Quote from ECMAScript Language Specification, section Date Time String Format:

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ
...
Z is the time zone offset specified as "Z" (for UTC) or either "+" or "-" followed by a time expression HH:mm

Apparently, you need to add a : in the timezone designator. This should work in 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);

For Twitter dates you can use the same strategy:

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);

发布评论

评论列表(0)

  1. 暂无评论