How to compare two dates in JavaScript
Comparing dates is fundamental for validation, sorting, and implementing date-based business logic in web applications. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented date comparisons in countless components including calendars, data tables, and form validation. From my expertise, the most straightforward and reliable solution is to use standard comparison operators directly on Date objects. JavaScript automatically converts Date objects to timestamps for comparison, making this approach both simple and efficient.
Use comparison operators directly on Date objects to compare dates.
const date1 = new Date('2023-01-01')
const date2 = new Date('2023-12-31')
const isEarlier = date1 < date2
JavaScript Date objects can be compared using standard operators like <
, >
, <=
, >=
, and ===
. When comparing, JavaScript automatically converts the Date objects to their numeric timestamp values (milliseconds since epoch), allowing direct comparison. For equality checks, use date1.getTime() === date2.getTime()
instead of ===
to ensure accurate comparison regardless of object reference. This works for any date comparison scenario including sorting arrays of dates.
Best Practice Note:
This is the same approach we use in CoreUI components for data table sorting and date range validation.
For timezone-independent comparisons, convert both dates to UTC using toISOString()
or compare using getTime()
method for precise timestamp comparison.