HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How do I compare two dates in JavaScript?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascripttwohowdatescompare

Problem

Comparing Date objects in JavaScript is often confusing. Equality is not as easy as you might think, you may have to consider timezones, and dates also act like numbers. That's a lot to wrap your head around, so let's take a look at each of these use-cases in detail.
Comparing two dates using the equality operators (== or ===) is ineffective, as it compares the objects by reference. Luckily, Date.prototype.toISOString() returns a string representation of the date in a standardized format, which can be used to compare two dates.
As mentioned previously, Date objects act like numbers. This means that you can use the less than operator (<) to check if a date comes before another date.
Similarly, you can use the greater than operator (>) to check if a date comes after another date.
Combining the previous two snippets, you can check if a date is between two other dates.

Solution

const isSameDate = (dateA, dateB) =>
  dateA.toISOString() === dateB.toISOString();

isSameDate(new Date('2020-10-20'), new Date('2020-10-20')); // true


As mentioned previously, Date objects act like numbers. This means that you can use the less than operator (<) to check if a date comes before another date.
Similarly, you can use the greater than operator (>) to check if a date comes after another date.
Combining the previous two snippets, you can check if a date is between two other dates.

Code Snippets

const isSameDate = (dateA, dateB) =>
  dateA.toISOString() === dateB.toISOString();

isSameDate(new Date('2020-10-20'), new Date('2020-10-20')); // true
const isBeforeDate = (dateA, dateB) => dateA < dateB;

isBeforeDate(new Date('2020-10-20'), new Date('2020-10-21')); // true
const isAfterDate = (dateA, dateB) => dateA > dateB;

isAfterDate(new Date('2020-10-21'), new Date('2020-10-20')); // true

Context

From 30-seconds-of-code: date-comparison

Revisions (0)

No revisions yet.