JavaScript: 3 ways to check if a date string is valid

Updated: March 7, 2023 By: Frienzied Flame Post a comment

Some common valid date string formats in JavaScript are:

  • ISO 8601 format: 2023-10-30 or 2023-10-30T16:30:00Z
  • Short date format: 11/30/2023
  • Long date format: October 30 2023 or 30 October 2022
  • RFC 2822 format: 30 Oct 2023 16:30:00 GMT
  • Time format: 16:30:00
  • Date and time format: 10/30/2023 16:30:00

This concise, straightforward article will walk you through 3 different ways to check whether a given string is a valid date string or not in JavaScript. Without any further ado, let’s get started.

Using the Date.parse() method

This method returns the number of milliseconds since midnight of January 1, 1970, for a given date string. If the date string is invalid or unrecognized, it returns NaN.

Example:

let dateString = "2023-10-30";
let timestamp = Date.parse(dateString);
if (isNaN(timestamp)) {
    console.log("Invalid date format");
} else {
    console.log("Valid date format");
}

Output:

Valid date format

Another example:

let dateString = "2023-10-30 12:00:00 abcxyz";
let timestamp = Date.parse(dateString);
if (isNaN(timestamp)) {
    console.log("Invalid date format");
} else {
    console.log("Valid date format");
}

Output:

Invalid date format

Using the Date() constructor

We can try to create a new Date object using the input string, then call the method toString() on that object and compare it to “Invalid Date”, as shown below:

const inputDate = '2023-01-31 aa';
const dateObject = new Date(inputDate);

if(dateObject.toString() === 'Invalid Date') {
    console.log('Invalid date string');
} else {
    console.log('Valid date string');
}

Output:

Invalid date string

Another example:

const inputDate = '2023-01-31 14:30:07';
const dateObject = new Date(inputDate);

if(dateObject.toString() === 'Invalid Date') {
    console.log('Invalid date string');
} else {
    console.log('Valid date string');
}

Output:

Valid date string

This approach is a bit more verbose than the previous one, and most developers will not like it. However, the most important thing is it works.

Using a third-party library

The famous package moment.js provides the isValid() method that can help us get the job done quickly.

Install moment.js:

npm i moment

Sample usage:

import moment from 'moment';

const dateString = "2024-01-01 12:00:00";

if(moment(dateString).isValid()){
    console.log("Valid date string");
} else {
    console.log("Invalid date string");
}

Output:

Valid date string

Conclusion

You’re explored 3 different techniques to determine whether a given string is a valid date string or not. In my opinion, the first approach is the best for most use cases because it is succinct and has an elegant syntax, as well as not depends on third-party package.