Skip to content

How to validate whether a string-value is a parsable date-format?

I am running the code below, checking if the string is a date. One of my input values is 'text' which returns the NaN value but my if clause does not work as expected.

function isDate(myDate) {
  console.log('myDate = ' + myDate);
  return Date.parse(new Date(myDate));
}

// var date1 = '1/5/22'; // good date
var date1 = 'test'; // bad date

var whatDate = isDate(date1);

console.log('date = ' + whatDate);

if (whatDate == 'NaN') {
  console.log('bad date');
} else {
  console.log('good date');
}

Answer

You’re almost there:

if(whatDate == 'NaN'){
    log.debug('bad date');
}else{
    log.debug('good date');
}

Instead of comparing whatDate to 'NaN' use the function isNaN():

if(isNaN(whatDate)){
    log.debug('bad date');
}else{
    log.debug('good date');
}

Alternatively, if you really want to compare to 'NaN' you first have to convert whatDate to a string:

if((whatDate + "") == 'NaN'){
    log.debug('bad date');
}else{
    log.debug('good date');
}

Is one possibility. Another way would be

if(whatDate.toString() == 'NaN'){
    log.debug('bad date');
}else{
    log.debug('good date');
}