I am stuck with checking if the string represents Date
. Currently I have a situation where I need to check if "Tue May 16 2017 00:00:00 GMT+0400 (Georgian Standard Time)"
this string represents Date
. I wrote the following code:
var tryConvert = new Date(input);
var tryMonth = tryConvert.getMonth();
if (!(tryMonth !== tryMonth)) {//checking for NaN
return true;
}
The problem is that input can be integer 96
and it successfully returns true. The desired behavior is that it should work only for Date
instances, ISO
strings /\d\d\d\d\-\d\d\-\d\dT\d\d\:\d\d\:\d\d/g
and Date.toString()
strings like "Tue May 16 2017 00:00:00 GMT+0400 (Georgian Standard Time)"
. How can I achieve this?
To make it more clear here is the full code:
function isDate(input) {
if (!input) {
return false;
}
if (input instanceof Date) {
return true;
}
var rx = /\d\d\d\d\-\d\d\-\d\dT\d\d\:\d\d\:\d\d/g;
var time = rx.exec(input);
if (time) {
return true;
}
if (typeof input === 'string' || input instanceof String) {
var tryConvert = new Date(input);
var tryMonth = tryConvert.getMonth();
if (!(tryMonth !== tryMonth)) {
return true;
}
}
return false;
};