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:
- validating booking dates
- checking deadlines
- preventing users from selecting past dates
- ordering records by date
- comparing start and end dates in forms
A key detail is that input format matters. Some date string formats are ambiguous, such as 01/02/2025, which may mean different things in different regions. A safer choice is the ISO-style format YYYY-MM-DD, especially when using HTML date inputs.
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('date2').value;
const firstDate = new Date(firstValue);
const secondDate = new Date(secondValue);
if (firstDate < secondDate) {
console.log('The first date is earlier than the second date.');
} else if (firstDate > secondDate) {
console.log('The first date is later than the second date.');
} else {
console.log('The two dates are the same.');
}
Checking that a date is not in the past
If you want to allow today and future dates, compare against today.
const enteredValue = document.getElementById('date1').value;
const enteredDate = new Date(enteredValue);
const today = new Date();
today.setHours(0, 0, 0, 0);
enteredDate.setHours(0, 0, 0, 0);
if (enteredDate >= today) {
console.log('The date is today or in the future.');
} else {
console.log('The date is in the past.');
}
Why setHours(0, 0, 0, 0) is useful
A Date includes both a date and a time. If you only care about the calendar day, resetting the time to midnight avoids accidental mismatches.
For example, if the current time is 3:00 PM, then new Date() represents today at 3:00 PM. A date created from 2025-06-10 may represent midnight. Without normalizing both values, comparing them can give results that look confusing.
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 Date(value1);
const date2 = new Date(value2);
console.log(date1 > date2);
Execution:
value1is the string'2025-06-20'value2is the string'2025-06-18'date1becomes aDateobject for June 20date2becomes aDateobject for June 18date1 > date2becomestrue
Checking against today step by step
const selectedDate = new Date('2025-06-10');
const today = new Date();
today.setHours(0, 0, 0, 0);
selectedDate.setHours(0, 0, 0, 0);
console.log(selectedDate >= today);
What happens:
todaystarts with the current date and current timesetHours(0, 0, 0, 0)resetstodayto midnightselectedDateis also reset to midnight- now the comparison uses only the day, not the time of day
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').value);
if (end < start) {
console.log('End date must be after start date.');
}
Normalizing time before comparison
function normalizeDate(date) {
const copy = new Date(date);
copy.setHours(0, 0, 0, 0);
return copy;
}
This is useful when your application cares about the calendar date rather than the exact time.
Using timestamps explicitly
Some teams prefer comparing numeric timestamps for clarity.
const date1 = new Date('2025-06-10').getTime();
const date2 = new Date('2025-06-11').getTime();
console.log(date1 < date2);
Validation helpers
In larger codebases, date logic is often wrapped in small reusable functions.
function isNotPast(value) {
const inputDate = new Date(value);
const today = new Date();
inputDate.setHours(0, 0, 0, 0);
today.setHours(0, 0, 0, 0);
return inputDate >= today;
}
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:
- Use
YYYY-MM-DD - Or parse the input manually if using custom formats
3. Forgetting that time is included
Broken example:
const today = new Date();
const selected = new Date('2025-06-10');
console.log(selected >= today);
If today is June 10 at 4 PM, and selected is June 10 at midnight, this will be false even though the dates look the same.
How to avoid it:
selected.setHours(0, 0, 0, 0);
today.setHours(0, 0, 0, 0);
4. Not checking for invalid dates
Broken example:
const date = new Date('not-a-date');
console.log(date < new Date());
This gives unreliable results because the date is invalid.
How to avoid it:
const date = new Date('not-a-date');
if (isNaN(date.getTime())) {
console.log('Invalid date');
}
5. Mutating a date accidentally
setHours() changes the original object.
const date = new Date();
date.setHours(0, 0, 0, 0);
If you still need the original time later, make a copy first:
const original = new Date();
const normalized = new Date(original);
normalized.setHours(0, 0, 0, 0);
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 |
Date object comparison vs getTime()
const d1 = new Date('2025-06-10');
const d2 = new Date('2025-06-11');
console.log(d1 < d2); // true
console.log(d1.getTime() < d2.getTime()); // true
Both work. Many beginners find direct comparison easier to read. Some developers prefer getTime() because it makes the numeric comparison explicit.
Comparing full timestamps vs calendar days
- Use full timestamp comparison when time matters
- Normalize both dates first when only the day matters
const a = new Date('2025-06-10T23:00:00');
const b = new Date('2025-06-10T08:00:00');
console.log(a > b); // true
These are the same day, but different times.
input type="date" vs plain text input
| Input type | Advantage | Limitation |
|---|---|---|
type="date" | Usually gives a clean YYYY-MM-DD value | Browser UI varies |
type="text" | Flexible format | Requires more validation and parsing |
If possible, use type="date" to make date input safer and easier to compare.
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, 0, 0);
d2.setHours(0, 0, 0, 0);
if (d1 >= d2) {
console.log('d1 is same day or later');
}
Quick rules
- Input values from text boxes are strings
- Convert strings before comparing
- Prefer
YYYY-MM-DDover ambiguous formats - Use
isNaN(date.getTime())to detect invalid dates - Reset time to midnight if you only care about the day
setHours()mutates the originalDate
Useful operators
<earlier than>later than<=earlier than or same>=later than or same===onDateobjects does not compare date values
Broken:
new Date('2025-06-10') === new Date('2025-06-10') // false
Correct:
new Date('2025-06-10').getTime() === new Date('2025-06-10').getTime() // true
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 getTime() instead.
What input format is safest for JavaScript dates?
YYYY-MM-DD is usually the safest choice for browser input, especially with input type="date".
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
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.