Emmanuel Akinfulubi

JavaScriptBasic

Compare two dates in JavaScript

Beginner · 3 min read

Is this coupon still valid? Has the deadline passed? Which order came first? Comparing two dates is one of the most common checks in real apps. JavaScript makes most of it easy, but it has one trap that catches nearly everyone, and this lesson shows it to you on purpose.

You will write a function called compareDates(a, b) that returns 'earlier', 'later' or 'the same'. Then you will sort a list of dates. You need to know what a function, an if statement and an array are. You should also know that new Date(2026, 8, 2) means 2 September 2026, because months count from 0.

A date is a number in disguise

JavaScript stores every date as a number of milliseconds since 1 January 1970. You can see that number with getTime():

JavaScript

const d = new Date(2026, 8, 2);
console.log(typeof d.getTime()); // number

When you use < or > on two dates, JavaScript turns each one into that number first, then compares the numbers. So "less than" means "earlier".

Objects and identity

A Date is an object. With objects, === doesn't compare what is inside. It asks: "are these the very same object?" Two dates made separately are two different objects, even if they hold the same moment. Think of two copies of the same book: same words, but not the same book.

Here is the exercise. Try it on your own first if you like, then read on.

7 Compare two dates for order

easy

Take two dates and report whether the first is earlier than, later than, or the same as the second.

Stuck? Three hints, smallest first
  1. 1. Comparing dates with < and > works, because they convert to numbers.
  2. 2. But == and === do not work: two Date objects are never the same object.
  3. 3. Compare getTime() values for equality.

Step 1: earlier and later

Start with < and >, which work exactly as you would hope.

Step 1

const first = new Date(2026, 8, 2);
const second = new Date(2026, 11, 25);
console.log(first < second); // true
console.log(first > second); // false

Step 2: the trap

Now make a second date for the same day and ask whether they are equal.

Step 2

const first = new Date(2026, 8, 2);
const duplicate = new Date(2026, 8, 2);
console.log(first === duplicate); // false
console.log(first == duplicate);  // false

Both lines print false, even though the dates are the same day. == doesn't help either, because both sides are objects, so it also compares identity. If you write if (dateA === dateB), that check is false every time you build the two dates separately.

The fix is to compare the numbers yourself:

JavaScript

const first = new Date(2026, 8, 2);
const duplicate = new Date(2026, 8, 2);
console.log(first.getTime() === duplicate.getTime()); // true

Step 3: the compare function

Put the two working checks first. If a date is neither earlier nor later, it must be the same moment, so you don't need an equality check at all.

Step 3

function compareDates(a, b) {
  if (a < b) return 'earlier';
  if (a > b) return 'later';
  return 'the same';
}

const first = new Date(2026, 8, 2);
const second = new Date(2026, 11, 25);
const duplicate = new Date(2026, 8, 2);
console.log(compareDates(first, second));    // earlier
console.log(compareDates(second, first));    // later
console.log(compareDates(first, duplicate)); // the same

Each return ends the function straight away, so the last line only runs when both checks were false.

Step 4: sort a list of dates

sort takes a compare function that gets two items and returns a number. Negative means the first goes first, positive means the second goes first. Subtracting two dates gives exactly that, because it subtracts their millisecond numbers.

Step 4

const first = new Date(2026, 8, 2);
const second = new Date(2026, 11, 25);
const dates = [second, first, new Date(2026, 5, 1)];
const sorted = dates.slice().sort((x, y) => x - y);
console.log(sorted.map((d) => d.getMonth() + 1)); // [ 6, 9, 12 ]

slice() makes a copy first, because sort changes the array it is called on. The map turns each date into its month number (adding 1, since months count from 0) so the result is easy to read: June, September, December.

The full solution

The complete answer compares the dates all three ways, shows the === trap next to the getTime() fix, and sorts a list. Press Run to see the output.

The answer

function compareDates(a, b) {
  // Less-than and greater-than work, because a Date converts to a number.
  if (a < b) return 'earlier';
  if (a > b) return 'later';
  return 'the same';
}

const first = new Date(2026, 8, 2);
const second = new Date(2026, 11, 25);
const duplicate = new Date(2026, 8, 2);

console.log(compareDates(first, second));
console.log(compareDates(second, first));
console.log(compareDates(first, duplicate));

// The trap: equality does NOT work on the objects themselves.
console.log('=== on two equal dates :', first === duplicate);   // false
console.log('getTime comparison     :', first.getTime() === duplicate.getTime());

// Which is why sorting needs a subtraction, not a comparison of objects:
const dates = [second, first, new Date(2026, 5, 1)];
const sorted = dates.slice().sort((x, y) => x - y).map((d) => d.getMonth() + 1);
console.log('sorted months:', sorted);

Output


      
6 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 6 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

6 checks

test('earlier', compareDates(first, second), 'earlier');
test('later', compareDates(second, first), 'later');
test('equal by value', compareDates(first, duplicate), 'the same');
test('but not equal by identity', first === duplicate, false);
test('getTime is how you test equality', first.getTime() === duplicate.getTime(), true);
test('sorting by subtraction works', sorted, [6, 9, 12]);

The asymmetry is the lesson. < and > convert both dates to numbers and work fine, but === compares object identity, so two dates for the same instant are never equal. Anyone who has written if (dateA === dateB) and watched it always be false has met this. Compare getTime(), or subtract.

Common mistakes

  • Using === to check two dates are equal. It compares objects, not moments, and is false for any two separately created dates. Compare getTime() values.
  • Comparing date strings. '9/2/2026' < '10/1/2026' compares text letter by letter and gets the order wrong. Compare Date objects or their numbers.
  • Sorting without a compare function. dates.sort() turns each date into text and sorts alphabetically, which puts "Fri" before "Mon".

Try it yourself

  1. Write isSameDate(a, b) that returns true when two dates hold the same moment.
  2. Write isExpired(expiry, now) that returns true once now is after expiry.
  3. Sort a list of dates from newest to oldest by changing one thing in the compare function.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.