Sling Academy
Home/JavaScript/JavaScript: 3 ways to check if a date string is valid

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

Last updated: March 07, 2023

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.

Next Article: JavaScript: 2 Ways to Convert a String into a Date Object

Series: Date and Time in JavaScript: Basic to Advanced Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration