I wrote the following JS function to check if a date comes in the right format and can be used further down in the application
const getInvalidDay = day => {
const date = new Date(day);
const dateToMoments = [date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()];
return dateToMoments.some(moment => moment !== 0);
};
An example snippet to see how it works
const getInvalidDay = day => {
const date = new Date(day);
const dateToMoments = [date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()];
return dateToMoments.some(moment => moment !== 0);
};
console.log('Should be true - not valid::: ', getInvalidDay('2021-03-16T09:00:00.000Z'));
console.log('Should be false - is valid::: ', getInvalidDay('2021-03-16'));
When we have all moments as 0
means the date is valid so we return false
instead, if some have !==0
then it is true
and the date is not valid
I was wondering if there is another way to achieve the same result
1 Answer 1
An invalid date will be recognized by the Date object, as you can see here.
console.log('invalid date: ', new Date('hello world').toString());
console.log('valid date: ', new Date('2022-07-03T12:55:10.176Z').toString());
Calling new Date() (the Date() constructor) returns a Date object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than -8,640,000,000,000,000 or greater than 8,640,000,000,000,000 milliseconds, it returns a Date object whose toString() method returns the literal string Invalid Date.
So by definition you could check if a date is invalid by simply doing:
console.log(new Date('hello world').toString() === "Invalid Date")
Another option is to check the date instance passed to isNaN
as indicated in this SO answer.
console.log('is valid: ', !isNaN(new Date('hello world')));
console.log('is valid: ', !isNaN(new Date()));