How to Compare Dates in JavaScript
Comparing dates is a fundamental operation in programming, essential for filtering data, validating deadlines, or scheduling events. In JavaScript, this is a straightforward task because Date objects can be compared directly using standard comparison operators like <, >, <=, and >=.
This guide will teach you the core principle of date comparison in JavaScript. You will learn how to check if a date is before, after, equal to, or between other dates, and how to compare a date to the current time to see if it's in the past or future.
The Core Method: Direct Comparison of Date Objects
JavaScript Date objects can be compared directly because the comparison operators (<, >) implicitly convert the dates to their numeric representation: the timestamp. A timestamp is the number of milliseconds that have elapsed since the Unix Epoch (January 1, 1970, 00:00:00 UTC).
When you write date1 < date2, JavaScript is effectively comparing date1.getTime() < date2.getTime(). This makes date comparisons simple, intuitive, and reliable.
How to Create Date Objects
To perform a comparison, you must first have valid Date objects.
// From an ISO 8601 string (YYYY-MM-DD) - Recommended
const date1 = new Date('2023-10-27');
// From the current time
const now = new Date();
// From individual components (Year, Month-Index, Day)
// Note: The month is 0-indexed (0 = January, 11 = December)
const date2 = new Date(2024, 0, 1); // January 1, 2024
Basic Examples: Is a Date Before, After, or Equal?
Let's see the comparison operators in action.
Problem: given two dates, how do we determine their relationship to each other?
// Problem: Compare these two dates.
const d1 = new Date('2023-09-01');
const d2 = new Date('2023-10-27');
Solution:
const d1 = new Date('2023-09-01');
const d2 = new Date('2023-10-27');
// Is d1 before d2?
console.log(d1 < d2); // Output: true
// Is d1 after d2?
console.log(d1 > d2); // Output: false
// Are they the same? (Only true if timestamps are identical)
const d3 = new Date('2023-09-01');
console.log(d1.getTime() === d3.getTime()); // Output: true
Practical Use Cases
With this basic principle, we can solve several common problems.
How to Check if a Date is in the Past
To check if a date is in the past, simply compare it to the current date and time.
function isInThePast(date) {
const now = new Date();
return date < now;
}
// Example Usage:
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
console.log(isInThePast(yesterday)); // Output: true
console.log(isInThePast(new Date('2099-01-01'))); // Output: false
How to Check if a Date is in the Future
To check if a date is in the future, you do the opposite comparison.
function isInTheFuture(date) {
const now = new Date();
return date > now;
}
// Example Usage:
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(isInTheFuture(tomorrow)); // Output: true
console.log(isInTheFuture(new Date('2000-01-01'))); // Output: false
How to Check if a Date is Between Two Other Dates
To check if a date falls within a range, you perform two comparisons.
function isBetween(date, start, end) {
return date >= start && date <= end;
}
// Example Usage:
const eventDate = new Date('2023-10-27');
const startDate = new Date('2023-10-01');
const endDate = new Date('2023-10-31');
console.log(isBetween(eventDate, startDate, endDate)); // Output: true
Important Note: Comparing by "Day" vs. "Time"
A common "gotcha" is that date comparisons are precise down to the millisecond. If you want to check if a date is "yesterday or earlier," you need to be careful with the current time.
Problem: a date of 2023-10-26T23:00 is technically before 2023-10-27T10:00 (today at 10 AM). But if you only care about the calendar day, this can cause issues.
Solution: to compare by day only, set the time component of both dates to midnight (00:00:00.000) before comparing.
function isBeforeToday(date) {
const today = new Date();
// Set the time of "today" to the very beginning of the day.
today.setHours(0, 0, 0, 0);
// Now the comparison is based purely on the calendar date.
return date < today;
}
const lastNight = new Date(); // e.g., '2023-10-26T23:00'
lastNight.setHours(lastNight.getHours() - 12);
const yesterday = new Date(); // e.g., '2023-10-26T10:00'
yesterday.setDate(yesterday.getDate() - 1);
console.log(isBeforeToday(lastNight)); // Output: false
console.log(isBeforeToday(yesterday)); // Output: true
This technique ensures your comparisons are "day-based" rather than "time-based," which is often the desired logic for user-facing applications.
Conclusion
Comparing dates in JavaScript is a simple and powerful feature once you understand the underlying principle.
Dateobjects can be compared directly using standard operators (<,>,<=,>=) because they are converted to numeric timestamps.- To check if a date is in the past or future, simply compare it to a
new Date()object. - For comparisons that should only consider the calendar day, remember to normalize the time part of your dates by setting the hours, minutes, and seconds to
0withdate.setHours(0, 0, 0, 0).