Categories
JavaScript Answers

How to compare two string dates in JavaScript?

Spread the love

Sometimes, we want to compare two string dates in JavaScript.

In this article, we’ll look at how to compare two string dates in JavaScript.

How to compare two string dates in JavaScript?

To compare two string dates in JavaScript, we can compare them after we convert the date strings to timestamps.

For instance, we write

const isLater = (str1, str2) => {
  return new Date(str1) > new Date(str2);
};

to define the isLater function.

In it, we convert str1 and str2 to Date objects.

Then we compare them directly with >.

The Date objects are converted to timestamps automatically before they’re compared.

Conclusion

To compare two string dates in JavaScript, we can compare them after we convert the date strings to timestamps.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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