Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

Today, I’m going to show how you validate string is a valid date or not in javascript, here I will use the Date.parse() method to check if the string is a valid date or not.

The Date.parse() method parses a string representation of a date and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

Let’s start today’s tutorial How to check if a string is a date in javascript?

Before going to code, let’s understand what we are going to do?

  1. Create two date string variables one is a valid date string and the second is a common string
  2. Use Date.parse() on both variable
  3. Console which string is a valid
// Create two date string variable one is valid date string and second is common string
const validDateStr = "2020-01-01";
const inValidDateStr = "abc";

// Use `Date.parse()` on both variable
// Console which string is a valid
if(Date.parse(validDateStr)){
  console.log("validDateStr is a valid date");
}

if(Date.parse(inValidDateStr)){
  console.log("inValidDateStr is a valid date");
}

When running the above program it should console 'validDateStr is a valid date' in the log. let’s check the output.

javascript, check if a string is a date example
javascript, check if a string is a date example

I hope it’s help you, All the best 👍.