const isObjectClass = (value: any, className: any) => (Object.prototype.toString.call(value) === `[object ${className}]`);
export const isDate = (value: any) => isObjectClass(value, 'Date');
const time = (time: Date): string => {
return ((isDate(time) && !isNaN(time)) ? time : new Date()).toISOString();
};
In the above function time, I am checking if the input is a valid Date object or not. If valid, it will return the string version of passed Date. If invalid, it will return the string version of the current date.
The problem with isDate() is, it will return true for input values new Date() and new Date(undefined)). To avoid this I used !isNaN() which return false in case of !isNaN( new Date(undefined) ).
Now the problem is typescript is not allowing me to pass Date object to isNaN function.
error
TS2345: Argument of type 'Date' is not assignable to parameter of type 'number'.
Any suggestions?
You can convert this date object to time (!isNaN(time.getTime())) like as follows,
const time = (time: Date): string => {
return ((isDate(time) && !isNaN(time.getTime())) ? time : new Date()).toISOString();
};
In here getTime method returns numeric value of the respective date object. So you can easily use this numeric value with isNaN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With