How to compare two dates
Short answer
The < and > operators compare dates as numbers of milliseconds:
const start = new Date(2025, 0, 10);
const end = new Date(2025, 1, 1);
console.log(start < end);Output:
trueEquality
To check equality, compare the numbers from getTime():
const a = new Date(2025, 4, 1);
const b = new Date(2025, 4, 1);
console.log(a.getTime() === b.getTime());Output:
trueThe same day
To ignore the time, compare the year, the month and the day:
const sameDay = (a, b) =>
a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
console.log(sameDay(new Date(2025, 4, 1, 9, 0), new Date(2025, 4, 1, 18, 30)));Output:
trueIs the date in the past
Compare with the current moment:
const deadline = new Date(2020, 0, 1);
console.log(deadline < new Date() ? 'expired' : 'active');Output:
expiredCommon mistake
=== compares date objects by reference, so two equal dates are not equal:
const a = new Date(2025, 4, 1);
const b = new Date(2025, 4, 1);
console.log(a === b);Output:
falseFunctions used in this recipe
- Date.prototype.getTime — Returns the date as a number of milliseconds.