Home > Enterprise >  Why is 1200 being recognized as a valid date with moment?
Why is 1200 being recognized as a valid date with moment?

Time:06-09

Hi I am looping through an array of objects and trying to change the values to true if the value is validated as a date but some values are being hit as well. I put examples of some values below.

const data1 = 1200;
const date = '2022-05-24T14:52:30.250Z';
console.log(moment(data1, moment.ISO_8601, true).isValid()); < --- expected to be false but returns true
console.log(moment(date, moment.ISO_8601, true).isValid()); < --- returns true

why is this? Thank you for the help.

CodePudding user response:

When the first value passed to moment is a number, it's treated as a time value, the format argument is ignored. Any number in the range ±8.64e15 will be treated as representing a valid date.

The number 1200 will be treated as 1200 milliseconds after the ECMAScript epoch of 1 Jan 1970 UTC, so 1970-01-01T00:00:01.200Z, which is a valid date.

console.log(moment(1200).utc().format('YYYY-MM-DD HH:mm:ss.SSS'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>

  • Related