(EDIT: I am using chrome console for the code below)
I realize that javascript Date() is deprecated, but it’s useful for something I’m currently working on; however there is a strange problem:
var x = new Date('999').getFullYear()
returns 999
while
var x = new Date('1000').getFullYear()
returns 999 as well, but
var x = new Date('10000').getFullYear()
returns 10000…
Does anyone know why do 4 digit numbers give the wrong .getFullYear()?
As the other answers suggest, you can’t rely on
Date.parseacross browsers, especially if you are dealing with dates before 1000 CE.As far as Chrome is concerned, it looks like the issue is how the browser deals with timezones. The following example suggests that before 1000 CE, Chrome parses the date in your local timezone on top of it; >= 1000 CE, it appears to first parse the date in UTC, then applies the timezone conversion:
I’d be inclined to see this as a bug, but perhaps the Chromium team thinks it’s a feature :).
The bottom line is that, if you want accurate date parsing for years, especially ancient years, you need to do some work yourself and/or use a library. Moment.js and Datejs both might help, but I doubt either deals well with ancient years. Moment.js seems to have the same issue (in Chrome):
The best way I know of to accurately set dates based on ancient years is generally to a) always use UTC, and b) set the date manually:
In Chrome at least, this works with both strings and integers.
You might also be interested in the
gregorianparser in the Timemap.js library, which handles ancient years with AD, CE, BC, and BCE extensions, as well as negative numbers.