Question
Compare Two Dates in JavaScript: Greater Than, Less Than, and Not in the Past
Question
I want to compare two date values in JavaScript to determine whether one is greater than or less than the other, and also check whether a date is not in the past. The date values will come from text box inputs.
For example, I need to:
- compare two entered dates
- check whether one date is earlier or later than another
- verify that a selected date is today or in the future
What is a reliable way to do this in JavaScript when the values come in as strings from input fields?
Short Answer
By the end of this page, you will understand how to compare dates in JavaScript by converting input strings into Date objects or timestamps. You will learn how to check whether one date is before or after another, how to test if a date is in the past, and how to avoid common problems with date parsing and time values.
Concept
JavaScript does not compare date strings reliably unless they are in a safe format and converted properly first. When dates come from text boxes, they usually arrive as strings, not as Date objects.
To compare them correctly, you should usually follow this process:
- Read the string from the input
- Convert it into a
Dateobject - Compare the numeric time values
A JavaScript Date internally stores a moment in time as a number: the number of milliseconds since January 1, 1970 UTC. Because of that, date comparisons are really number comparisons.
For example:
const date1 = new Date('2025-06-01');
const date2 = new Date('2025-06-10');
console.log(date1 < date2); // true
This works because JavaScript converts each Date to its underlying numeric value when using comparison operators like <, >, <=, and >=.
Why this matters in real programs:
Mental Model
Think of a date like a numbered position on a timeline.
- A date further to the right is later
- A date further to the left is earlier
- Today is the current marker on that timeline
When you compare two dates in JavaScript, you are really asking:
- is position A before position B?
- is position A after position B?
- is position A at or after today?
If the values come from text boxes, they start as labels written on paper. JavaScript cannot safely place them on the timeline until you convert them into real date values.
Syntax and Examples
The basic pattern is:
const inputValue = '2025-06-15';
const date = new Date(inputValue);
Then compare dates with normal comparison operators:
const startDate = new Date('2025-06-10');
const endDate = new Date('2025-06-15');
console.log(startDate < endDate); // true
console.log(startDate > endDate); // false
console.log(startDate <= endDate); // true
console.log(startDate >= endDate); // false
Comparing values from text boxes
const firstValue = document.getElementById('date1').value;
const secondValue = document.getElementById().;
firstDate = (firstValue);
secondDate = (secondValue);
(firstDate < secondDate) {
.();
} (firstDate > secondDate) {
.();
} {
.();
}
Step by Step Execution
Consider this example:
const firstDate = new Date('2025-06-10');
const secondDate = new Date('2025-06-15');
if (firstDate < secondDate) {
console.log('firstDate comes earlier');
}
Step by step:
new Date('2025-06-10')creates aDateobject for June 10, 2025.new Date('2025-06-15')creates aDateobject for June 15, 2025.- JavaScript compares the two dates using
<. - Internally, both dates are converted to numeric timestamps.
- The timestamp for June 10 is smaller than the timestamp for June 15.
- The condition is
true, so the message is printed.
Traceable example with user input
const value1 = '2025-06-20';
const value2 = '2025-06-18';
const date1 = new (value1);
date2 = (value2);
.(date1 > date2);
Real World Use Cases
Date comparison is common in many kinds of applications.
Forms and validation
- Prevent users from choosing a meeting date in the past
- Check that an end date is after a start date
- Validate that a subscription renewal date is still valid
Booking systems
- Ensure check-out is after check-in
- Prevent reservations for expired dates
- Sort availability by earliest opening date
Task and deadline tracking
- Mark tasks as overdue
- Show upcoming deadlines
- Filter future events only
APIs and data processing
- Compare timestamps from server responses
- Reject expired tokens or session dates
- Process records only within a valid date range
Reporting dashboards
- Filter rows between two dates
- Compare today with scheduled events
- Group data into past, current, and future periods
Real Codebase Usage
In real projects, developers rarely compare raw input strings directly. They usually add validation and normalize the values before comparing.
Common patterns
Guard clauses
Stop early if a value is missing or invalid.
const value = document.getElementById('date1').value;
if (!value) {
console.log('Please enter a date.');
return;
}
const date = new Date(value);
if (isNaN(date.getTime())) {
console.log('Invalid date.');
return;
}
Start/end date validation
const start = new Date(document.getElementById('start').value);
const end = new Date(document.getElementById().);
(end < start) {
.();
}
Common Mistakes
Here are some common beginner mistakes when comparing dates in JavaScript.
1. Comparing strings instead of dates
Broken example:
const a = '12/01/2025';
const b = '02/01/2025';
console.log(a > b);
This compares text, not actual calendar values.
How to avoid it:
- Convert strings to
Dateobjects first - Prefer
YYYY-MM-DDformat when possible
const a = new Date('2025-12-01');
const b = new Date('2025-02-01');
console.log(a > b);
2. Using ambiguous date formats
Broken example:
new Date('01/02/2025');
This may be interpreted differently depending on environment or locale.
How to avoid it:
Comparisons
| Approach | Best for | Example | Notes |
|---|---|---|---|
Compare Date objects directly | Simple date comparisons | date1 < date2 | JavaScript converts them to timestamps |
Compare timestamps with getTime() | Explicit numeric comparison | date1.getTime() < date2.getTime() | Useful for clarity and debugging |
| Compare raw strings | Rarely safe | '2025-06-10' < '2025-06-11' | Only safe in consistent ISO-like formats, but still less clear |
| Normalize to midnight first | Calendar-day comparisons | date.setHours(0,0,0,0) | Important when time should be ignored |
Cheat Sheet
// Read from input
const value = document.getElementById('myDate').value;
// Convert string to Date
const date = new Date(value);
// Check for invalid date
if (isNaN(date.getTime())) {
console.log('Invalid date');
}
// Compare two dates
if (date1 < date2) {
console.log('date1 is earlier');
}
if (date1 > date2) {
console.log('date1 is later');
}
if (date1.getTime() === date2.getTime()) {
console.log('same exact time');
}
// Ignore time and compare only date
const d1 = new Date(date1);
const d2 = new Date(date2);
d1.setHours(0, 0, , );
d2.(, , , );
(d1 >= d2) {
.();
}
FAQ
How do I compare two dates in JavaScript?
Convert both values into Date objects, then use <, >, <=, or >=, or compare getTime() values.
Can I compare date strings directly?
Only in very limited cases with consistent ISO-like strings. In general, convert them to Date objects first.
How do I check if a date is not in the past?
Create a Date for the input and compare it with today. If you only care about the day, reset both times to midnight first.
Why does comparing today's date sometimes fail?
Because Date includes time. A selected date at midnight can appear earlier than the current moment later in the day.
How do I validate a date from a text box?
Convert it with new Date(value) and check isNaN(date.getTime()).
Is === good for comparing two dates?
Not for comparing date values. === checks whether two objects are the same object in memory. Use instead.
Mini Project
Description
Build a small date validation tool for a form. The user enters a start date and an end date, and the script checks whether both dates are valid, whether the start date is not in the past, and whether the end date is the same as or later than the start date. This demonstrates practical date parsing, validation, and comparison from user input.
Goal
Create a JavaScript form validator that accepts two date inputs and displays whether the dates are valid and in the correct order.
Requirements
- Read a start date and end date from two input fields.
- Validate that both values are present and are valid dates.
- Check that the start date is today or in the future.
- Check that the end date is the same as or later than the start date.
- Display a clear success or error message.
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.