Check string is date or not in JavaScript

To check a string value is a date, there are many ways to do that. But problem occur when string is a number, since a number can be converted into a valid date. We will try to solve this problem as much as possible. Let start

Case 1: when value is not a number

Solution 1: Using Date.parse

Date.parse returns a timestamp in milliseconds if the string is a valid date. Otherwise, it returns NaN . Means it is NaN then it is not a valid date.

let d = "hi"
isNaN(Date.parse(d)) // true

Solution 2: Using Date Constructor

We can use the Date constructor to check whether a string is a valid date or not. If we pass in a string that isn’t a valid date string, it’ll return 'Invalid Date'.

let d = "hi"
new Date(d).toString() === "Invalid Date" // true

OR

// If you are not using to string then you have to use == not === 
new Date(d) == "Invalid Date" // true

Case 2: when string value is number

For this scenario where a given string is a number the with assumption that we will not pass date as number, or we know our date format.

function isDate(dateStr) {
  if(isNaN(dateStr)) {//Checked for numeric
    var dt=new Date(dateStr);
    if(isNaN(dt.getTime())){ //Checked for date if it NaN then it is not date
      return false; //Return string if not date.
    }else {
      return true; //Return date **Can do further operations here.
    }
  } else {
    return false; //Return string as it is number
  }
}

let d = '3"
isDate(d) // false

Leave a Reply