Question

Compare Two Dates in JavaScript: Greater Than, Less Than, and Not in the Past

javascriptdatedatetimecompare

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:

  1. Read the string from the input
  2. Convert it into a Date object
  3. 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.

Take Quiz

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:

  1. new Date('2025-06-10') creates a Date object for June 10, 2025.
  2. new Date('2025-06-15') creates a Date object for June 15, 2025.
  3. JavaScript compares the two dates using <.
  4. Internally, both dates are converted to numeric timestamps.
  5. The timestamp for June 10 is smaller than the timestamp for June 15.
  6. 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:

  • value1 is the string '2025-06-20'
  • value2 is the string '2025-06-18'
  • date1 becomes a Date object for June 20
  • date2 becomes a Date object for June 18
  • date1 > date2 becomes true

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:

  • today starts with the current date and current time
  • setHours(0, 0, 0, 0) resets today to midnight
  • selectedDate is 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
Take Quiz

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 Date objects first
  • Prefer YYYY-MM-DD format 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

ApproachBest forExampleNotes
Compare Date objects directlySimple date comparisonsdate1 < date2JavaScript converts them to timestamps
Compare timestamps with getTime()Explicit numeric comparisondate1.getTime() < date2.getTime()Useful for clarity and debugging
Compare raw stringsRarely safe'2025-06-10' < '2025-06-11'Only safe in consistent ISO-like formats, but still less clear
Normalize to midnight firstCalendar-day comparisonsdate.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 typeAdvantageLimitation
type="date"Usually gives a clean YYYY-MM-DD valueBrowser UI varies
type="text"Flexible formatRequires more validation and parsing

If possible, use type="date" to make date input safer and easier to compare.

Take Quiz

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-DD over ambiguous formats
  • Use isNaN(date.getTime()) to detect invalid dates
  • Reset time to midnight if you only care about the day
  • setHours() mutates the original Date

Useful operators

  • < earlier than
  • > later than
  • <= earlier than or same
  • >= later than or same
  • === on Date objects 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".

Take Quiz

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

  1. Read a start date and end date from two input fields.
  2. Validate that both values are present and are valid dates.
  3. Check that the start date is today or in the future.
  4. Check that the end date is the same as or later than the start date.
  5. Display a clear success or error message.
Take Quiz

Keep learning

Related questions

View more