Categories
JavaScript Answers

How to Check if a String is a Date String with JavaScript?

Spread the love

Sometimes, we may want to check if a string is a date string with JavaScript.

In this article, we’ll look at how to check if a string is a date string with JavaScript.

Using the Date.parse() Method

One way to check if a string is date string with JavaScript is to use the Date.parse method.

To do this, we write:

console.log(Date.parse('2020-01-01'))
console.log(Date.parse('abc'))

Date.parse returns a timestamp in milliseconds if the string is a valid date.

Otherwise, it returns NaN .

So the first console log will log 1577836800000 and the 2nd one will log NaN .

Using moment.js

Another way to check if a date is a valid date is to use moment.js’ isValid method.

For instance, we can write:

console.log(moment("06/22/2015", "MM/DD/YYYY", true).isValid())

and we see true logged since ”06/22/2015" can be parsed into a date.

Using the Date Constructor

We can also check if a date is a valid date with the Date constructor.

If we pass in a string that isn’t a valid date string, it’ll return 'Invalid Date' .

So we can check for that to see if it’s a date.

In addition, we can parse the date string into a timestamp and check if it returns NaN with the isNaN function.

Therefore, having both checks together lets us check if a string is a date string reliably.

For instance, we can write:

const isDate = (date) => {
  return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
}

console.log(isDate('2020-01-01'))
console.log(isDate('abc'))

We create the isDate function to add both checks.

The date parameter is a string to check.

So we get true and false from the console logs respectively.

Conclusion

We can check if a string is a date string with JavaScript by using native date methods or moment.js.

One reply on “How to Check if a String is a Date String with JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *