Compare two dates with JavaScript
How can you compare two dates using JavaScript, and what methods are available?Want to check if one date comes before, after, or equals another in JavaScript? Let’s explore simple ways to compare dates using built-in objects and methods like getTime() or direct comparison.
If you’ve ever tried comparing two dates in JavaScript using == or ===, you might’ve been surprised by the result. That’s because comparing date objects directly doesn’t give you the result you’d expect—it checks if the two references are exactly the same, not if the values are equal.
Here's the right way to compare dates:
Use the .getTime() method to compare the numeric time values of two dates.
const date1 = new Date('2023-05-01');
const date2 = new Date('2023-05-01');
if (date1.getTime() === date2.getTime()) {
console.log('Dates are equal');
}
Other comparison options:
You can also use <, >, <=, and >= operators, which work directly on date objects.
if (date1 < date2>
- Use getTime() or .valueOf() to get the numeric timestamp (in milliseconds).
- Consider using libraries like Moment.js or date-fns for more complex comparisons (e.g., ignoring time, comparing only dates, etc.).
So yeah, comparing dates in JavaScript is pretty straightforward once you know the trick—just don’t trust direct equality checks between date objects unless you’re comparing their time values!