0
0
JavascriptHow-ToBeginner · 3 min read

How to Compare Two Dates in JavaScript: Simple Guide

To compare two dates in JavaScript, convert them to Date objects and use comparison operators like <, >, or ===. You can also compare their time values using getTime() for precise equality or ordering.
📐

Syntax

To compare two dates, first create Date objects. Then use comparison operators or the getTime() method to compare their numeric time values.

  • date1 < date2: checks if date1 is before date2.
  • date1 > date2: checks if date1 is after date2.
  • date1.getTime() === date2.getTime(): checks if both dates are exactly the same moment.
javascript
const date1 = new Date('2024-06-01');
const date2 = new Date('2024-06-02');

// Compare using operators
console.log(date1 < date2);  // true
console.log(date1 > date2);  // false

// Compare exact equality
console.log(date1.getTime() === date2.getTime());  // false
Output
true false false
💻

Example

This example shows how to compare two dates to find which one is earlier, later, or if they are the same.

javascript
const dateA = new Date('2024-06-10T10:00:00');
const dateB = new Date('2024-06-10T15:00:00');

if (dateA.getTime() === dateB.getTime()) {
  console.log('Dates are the same');
} else if (dateA < dateB) {
  console.log('dateA is before dateB');
} else {
  console.log('dateA is after dateB');
}
Output
dateA is before dateB
⚠️

Common Pitfalls

Many beginners try to compare dates directly as strings or objects, which does not work as expected because Date objects are not primitive values.

Also, using == or === on Date objects compares references, not the actual date values.

javascript
const d1 = new Date('2024-06-01');
const d2 = new Date('2024-06-01');

// Wrong: compares object references
console.log(d1 === d2);  // false

// Right: compare time values
console.log(d1.getTime() === d2.getTime());  // true
Output
false true
📊

Quick Reference

OperationDescriptionExample
Check if date1 is before date2Use < operatordate1 < date2
Check if date1 is after date2Use > operatordate1 > date2
Check if dates are exactly equalCompare getTime() valuesdate1.getTime() === date2.getTime()
Create a Date objectUse new Date()const d = new Date('2024-06-01')

Key Takeaways

Always convert strings or other formats to Date objects before comparing.
Use comparison operators (<, >) to check order between dates.
Use getTime() to compare exact equality of two dates.
Never compare Date objects directly with === or == as it compares references.
Remember Date objects represent moments in time including hours, minutes, and seconds.