1

I am trying to parse a dynamically created date format using Date.Parse function.But it is displaying 'NaN' in IE while running and works fine on Chrome.

Here is my sample code,

       var date = 2019 + '-' + 2 + '-' + 29;
       Date.parse(date)

When i tried using directly Date.Parse(2019-2-29) its working.

David
  • 380
  • 2
  • 14

2 Answers2

0

You should provide correctly formatted date

The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

ex. '04 Dec 1995 00:12:00 GMT'

maximelian1986
  • 2,308
  • 1
  • 18
  • 32
0

You shouldn't use Date.parse in an ES5 environment, because it might not work correctly. However, below is an example showing you how to work around it (not tested thoroughly, you might have to tweak it).

var date = '2019-02-28T14:05:23';

function isoToMS (iso) {
  var r = null;
  if (Date.parse) {
    r = Date.parse(iso);
  }
  if (!r || !Number.prototype.isPrototypeOf(r)) {
    r = iso.split(/[\-T:]/g).reduce(function (d, partial, i) {
      if (i < 1) { d.setFullYear(Number(partial)); }
      else if (i < 2) { d.setMonth(Number(partial) - 1); }
      else if (i < 3) { d.setDate(Number(partial)); }
      else if (i < 4) { d.setHours(Number(partial)); }
      else if (i < 5) { d.setMinutes(Number(partial)); }
      else if (i < 6) { d.setSeconds(Number(partial)); }
      return d;
    }, new Date());

    if (!/T\d+/g.test(iso)) {
      // note: Date.parse converts ISO without time information to UTC
      r.setMinutes(r.getMinutes() + r.getTimezoneOffset());
    }
  }
  return +r;
}

console.log(isoToMS(date));
David
  • 3,552
  • 1
  • 13
  • 24
  • This is not a good solution as 1) It does not allow for cases where the string is incorrectly parsed to a valid Date, 2) `Number.prototype.isPrototypeOf` returns *false* for **every** possible value returned by Date.parse, so effectively it always uses the manual parse and doesn't use Date.parse at all 3) It always parses the string as local, even when it should be UTC, 4) If the "T" is missing it returns null 5) if the T and time are missing, it does not set the time correctly (and arguably should parse the date as local, not UTC). – RobG Jan 29 '19 at 20:51