0

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;
};
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75

1 Answers1

1

For your use case, combining your check if input is a string with a check if it's a parseable number or not should do the trick.

Here I've added added this check where you check if input is a string:

if ((typeof input === 'string' || input instanceof String) && isNaN(input)) {
    var tryConvert = new Date(input);
    var tryMonth = tryConvert.getMonth();
    if (!(tryMonth !== tryMonth)) {
        return true;
    }
}

return false;

Basically, this returns false if input is a string containing 96, 5555 or any other parseable number but actual date strings such as Tue May 16 2017 00:00:00 GMT+0400 (Georgian Standard Time) are not parseable numbers so they will pass the isNaN() check and proceed to the conversion test.

You can probably remove the RegExp test as well since it only tests one particular date format.

Lennholm
  • 7,205
  • 1
  • 21
  • 30