4

Why when a string of numbers of different length is passed to Date in Javascript sometimes returns a Date Object and sometimes Invalid Date.

For example :

  1. new Date('123456') -> Tue Jan 01 123456 00:00:00 GMT+0530

  2. new Date('1234567') -> Invalid Date

  3. new Date('999999') -> Invalid Date

Prabhat
  • 41
  • 1
  • `'123456'` is a year within the valid range of [Date](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date), the others are not. `The JavaScript Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.` – Xotic750 Apr 26 '17 at 15:38
  • 1
    Possible duplicate of [Minimum and maximum date](http://stackoverflow.com/questions/11526504/minimum-and-maximum-date) – Vasan Apr 26 '17 at 15:39
  • 1
    and [Weird error with Date, “uncaught illegal access”](http://stackoverflow.com/questions/27598612/weird-error-with-date-uncaught-illegal-access) – Kirill Matrosov Apr 26 '17 at 15:42

1 Answers1

2

The way you are using the date constructor, the string is interpreted as the year. However, as Xotic750 already stated, dates in Javascript can only be in a range of -100,000,000 days to 100,000,000 days relative to 01 Jan, 1970 UTC. That means '123456' is in the range, but '1234567' and '999999' are not.

Note that using the Date constructor with a string is strongly discouraged because of inconsistency between browsers. It would be better to parse the date yourself and use the constructor taking years, months etc.