0

Chrome showing result as expected but IE-8 giving NAN when i execute the following:

Chrome:

d = new Date("2014 12 01") // results Mon Dec 01 2014 00:00:00 GMT+0500 (Pakistan Standard Time)

IE-8:

d = new Date("2014 12 01") // results NaN undefined
scunliffe
  • 62,582
  • 25
  • 126
  • 161
Ali Shaukat
  • 935
  • 6
  • 20
  • 4
    `Date` has nothing whatsoever to do with jQuery – T.J. Crowder Jun 04 '15 at 11:44
  • 2
    @RohitArora: No, because that's about parsing the format that the specification added in ES5. This is about parsing a random non-standard format. – T.J. Crowder Jun 04 '15 at 11:44
  • That's because Chrome is smarter and less strict than IE8. "2014 12 01" is all but a correct date format. Chrome is just smart enough to understand it nonetheless, but strictly speaking, it shouldn't. – Jeremy Thille Jun 04 '15 at 11:47

1 Answers1

3

The format you're trying to parse doesn't match the only specific format that new Date is required to parse. To parse it reliably cross-browser, you need to parse it explicitly — either in your own code, which can be trivially done with a regex, or using a library like MomentJS and telling it what the format is.

The trivial regex solution:

// NOTE! Uses local time.
var yourString = "2014 12 01";
var parts = yourString.match(/^(\d{4}) (\d{2}) (\d{2})$/);
if (parts) {
  var date = new Date(+parts[1], +parts[2] - 1, +parts[3]);
  alert(date.toString());
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875