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.

7 replies on “How to Check if a String is a Date String with JavaScript?”

I have observed that Date.parse behaves weird for strings starting with alphabets and end with a space followed by certain numbers. For ex:

Date.parse(‘abc 12’); returns 1007145000000
Date.parse(‘abc 99’); returns 915129000000
Date.parse(‘abc 11’); returns 1004553000000
Date.parse(‘abc 112’)); returns -58632875608000

but the behavior is different for following examples:
Date.parse(‘abc 21’); returns NaN
Date.parse(‘abc 30′); returns NaN
Date.parse(’12 abc’); returns NaN
Date.parse(‘abc 12 abc’); returns NaN
Date.parse(’12 abc 12′); returns NaN

My project requires to identify type of an attribute, whether it’s a string or a Date. We have following logic to identify if string is a date:
const isDate = (a) => !isNaN(Date.parse(a)) ? ‘date’ : false;
but it fails for strings like ‘abc 12’. It identifies them as ‘date’.
Why does it fail for such strings and what can I do, so that it will be able to identify ‘actual’ dates as ‘date’ and strings like ‘abc 12’ as ‘string’

Leave a Reply

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