The following answer, in addition to what already was explained about how to detect a NaN
value, wants to reach further.
A check or test function especially if it also carries the prefix is
in its name should always return exclusively a boolean value.
- Thus the OP firstly would implement such a function in a way a user would expect it to work.
- Secondly the OP had do deal with the
NaN
issue exactly once within the test function's implementation.
Edit according and thanks to the clarification of RobG
... and ... according to the ECMAScript's spec with instantiating a Date
object, the argument passed to the constructor function will be parsed and assigned to the internal thisTimeValue
slot. The number type of the latter is the NaN
value for a non parsable (invalid) argument.
Any valueOf
related operation does return the value of the internal thisTimeValue
slot.
Any toString
related operation will compute a date string format from the latter value. For a thisTimeValue
of NaN
the returned string value has to be 'Invalid Date'
.
Thus a validation / test implementation could have been something like ...
function isParsableDateRepresentative(...args) {
return String(new Date(...args)) !== 'Invalid Date';
}
... but preferably it should be closer to the next provided one ...
function isParsableDateRepresentative(...args) {
return !Number.isNaN(new Date(...args).valueOf());
}
Tests:
function isParsableDateRepresentative(...args) {
return !Number.isNaN(new Date(...args).valueOf());
}
console.log('new Date("1/5/22") ...', new Date("1/5/22"));
console.log(
'isParsableDateRepresentative("1/5/22") ...',
isParsableDateRepresentative("1/5/22")
);
console.log('\nnew Date("test") ...', new Date("test"));
console.log(
'isParsableDateRepresentative("test") ...',
isParsableDateRepresentative("test")
);
console.log('\nnew Date(new Date("test")) ...', new Date(new Date("test")));
console.log(
'isParsableDateRepresentative(new Date("test")) ...',
isParsableDateRepresentative(new Date("test"))
);
console.log('\nnew Date() ...', new Date());
console.log(
'isParsableDateRepresentative() ...',
isParsableDateRepresentative()
);
console.log('\nnew Date(null) ...', new Date(null));
console.log(
'isParsableDateRepresentative(null) ...',
isParsableDateRepresentative(null)
);
console.log('\nnew Date(undefined) ...', new Date(undefined));
console.log(
'isParsableDateRepresentative(undefined) ...',
isParsableDateRepresentative(undefined)
);
console.log('\nnew Date("") ...', new Date(""));
console.log(
'isParsableDateRepresentative("") ...',
isParsableDateRepresentative("")
);
.as-console-wrapper { min-height: 100%!important; top: 0; }