To compare two dates accurately in JavaScript, compare their numeric timestamps in milliseconds using .getTime() (such as date1.getTime() === date2.getTime()). Operators like <, <=, >, and >= compare dates as numbers automatically, whereas === only checks whether two variables point to the exact same object in memory.

Why === Fails When Comparing Two Dates

Every time you run new Date(…), JavaScript creates a new date object in memory. Even when two Date objects represent the exact same moment, === treats them as two separate objects and returns false. Calling .getTime() converts each date into the number of milliseconds since January 1, 1970 (UTC), letting you compare them reliably as plain numbers.

JavaScript
const firstTime = new Date("2026-11-23T10:00:00Z");
const secondTime = new Date("2026-11-23T10:00:00Z");
const laterTime = new Date("2026-11-23T14:30:00Z");

// Wrong: compares object references in memory, not actual time
console.log(firstTime === secondTime); // false

// Right: compares exact millisecond timestamps
console.log(firstTime.getTime() === secondTime.getTime()); // true
console.log(firstTime.getTime() < laterTime.getTime());   // true
console.log(laterTime.getTime() > firstTime.getTime());   // true

Checking Invalid Dates and Time Differences

Sometimes a date string from user input or an API is invalid, which makes .getTime() return NaN. Checking Number.isNaN(date.getTime()) before comparing helps prevent subtle bugs, and subtracting two .getTime() values lets you calculate the exact time difference in milliseconds.

JavaScript
const startDate = new Date("2026-11-23T09:00:00Z");
const endDate = new Date("2026-11-23T11:00:00Z");
const badDate = new Date("not-a-date");

if (!Number.isNaN(startDate.getTime()) && !Number.isNaN(endDate.getTime())) {
  const diffMilliseconds = endDate.getTime() - startDate.getTime();
  const diffHours = diffMilliseconds / (1000 * 60 * 60);
  console.log(diffHours); // 2
}

console.log(Number.isNaN(badDate.getTime())); // true