markzzz
markzzz

Reputation: 47945

Date.getTime() returns NaN for ISO/Twitter API dates in IE11

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.

Upvotes: 2

Views: 7504

Answers (1)

Salman Arshad
Salman Arshad

Reputation: 272116

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

Upvotes: 6

Related Questions