Compare two dates in JavaScript
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
var first = new Date('01/21/2020'); var second = new Date('01/25/2020'); if (first < second) { console.log(`${first} is less than ${second}`); } else if (first > second) { console.log(`${first} is greater than ${second}`); } else { console.log(`${first} is equal to ${second}`); } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
var first = '2020/01/25'; var second = '2020/01/20'; if (first < second) { console.log(`${first} is less than ${second}`); } else if (first > second) { console.log(`${first} is greater than ${second}`); } else { console.log(`${first} is equal to ${second}`); } |
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 >=.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var moment = require('moment'); var first = new moment('01/25/2020', 'L'); var second = new moment('January 15, 2020', 'LL'); if (first < second) { console.log(`${first} is less than ${second}`); } else if (first > second) { console.log(`${first} is greater than ${second}`); } else { console.log(`${first} is equal to ${second}`); } |
That’s all about comparing two dates in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)