Peter Weightman
Back

Javascript dates beyond the year 9999

Recently we had a bug where a date had tried to the database in the following format: '+012021-01-01T00:00:00.000Z', which isn't a valid date string. Turns out it had come from a mixture of a strange javascript date bug and an OCR mistake. A date had been OCR'd as 01 / 01 12021 (which should've read 01 / 01 / 2021). This was parsed as '12021-01-01', and set as the value of a date input. Then before adding to the database, we take the input value and convert to an ISO string.

On Chrome/Edge (v90), Safari (v13), and Node (v14):

console.log(new Date('2021-01-01').toISOString());
// -> '2021-01-01T00:00:00.000Z'
console.log(new Date('12021-01-01').toISOString());
// -> '+012021-01-01T00:00:00.000Z'

Interestingly, on Firefox (v88) it'll give an error for the date:

console.log(new Date('2021-01-01').toISOString());
// -> '2021-01-01T00:00:00.000Z'
console.log(new Date('12021-01-01').toISOString());
// -> Uncaught RangeError: invalid date

However, even on Firefox, if you have a date input and set its value to '12021-01-01' then do input.checkValidity(), it'll return true.

I think probably the best fix is to put max="9999-12-31" on any date inputs.