This post will discuss how to compare two date strings in JavaScript. The solution should determine whether the first date string is greater than, less than, or equal to the second date string.

Assume that the given string values represent a valid date, specified in a format that is the version of ISO 8601 calendar date.

1. Using Date Object

Here, the idea is to convert the given strings into Date objects using the Date() constructor. Then compare both Date objects using relational operators >, <, <= or >=. The following example demonstrates.

Download  Run Code

 
If given strings are provided in a year-month-date format, the comparison will work without converting the strings into a Date object. This is demonstrated below, where the strings are compared using lexicographic order, i.e., in dictionary order.

Download  Run Code

 
Moment.js is a lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates. You can use it to compare two date strings using relational operators >, <, <= or >=.

Download Code

That’s all about comparing two dates in JavaScript.