Compare Dates in JavaScript with Examples

Learn how to compare dates in JavaScript with comparison operators, getTime(), and valueOf(), plus how to avoid timezone mistakes.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

Compare Dates in JavaScript with Examples

Comparing dates in JavaScript is common when you need to sort records, validate deadlines, or check whether one date is earlier than another. The important detail is that Date values are objects, so the comparison method matters.

The standard options are comparison operators, getTime(), and valueOf(). If you later need a normalized text form, JavaScript date to ISO string is the natural follow-up topic.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Method 1: Compare dates with operators

> and < compare the underlying numeric time value of the date objects.

javascript
const date1 = new Date("2023-03-01");
const date2 = new Date("2022-10-31");

console.log("date-compare:", date1 > date2);
Output

You should see one line logging date-compare: true.

This is the fastest way to compare two dates when you already have Date objects.


Method 2: Compare dates with getTime()

getTime() returns milliseconds since the Unix epoch, which makes the comparison explicit.

javascript
const date1 = new Date("2023-03-01");
const date2 = new Date("2022-10-31");

console.log("date-time:", date1.getTime() > date2.getTime());
Output

You should see one line logging date-time: true.

Use this when you want the comparison to be obvious to anyone reading the code.


Method 3: Compare dates with valueOf()

valueOf() returns the primitive time value of the date object.

javascript
const date1 = new Date("2023-01-01");
const date2 = new Date("2023-01-01");

console.log("date-equal:", date1.valueOf() === date2.valueOf());
Output

You should see one line logging date-equal: true.

This is useful when you need exact equality instead of just earlier-or-later checks.


Summary

To compare dates in JavaScript, use the comparison operators for simple ordering, getTime() for explicit numeric comparison, and valueOf() when you need the raw date value. Keep timezone handling in mind if the dates come from different sources.


Official documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …