snippetjavascriptTip
How do I compare two dates in JavaScript?
Viewed 0 times
javascripttwohowdatescompare
Problem
Comparing
Comparing two dates using the equality operators (
As mentioned previously,
Similarly, you can use the greater than operator (
Combining the previous two snippets, you can check if a date is between two other dates.
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')); // trueAs 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')); // trueconst isBeforeDate = (dateA, dateB) => dateA < dateB;
isBeforeDate(new Date('2020-10-20'), new Date('2020-10-21')); // trueconst isAfterDate = (dateA, dateB) => dateA > dateB;
isAfterDate(new Date('2020-10-21'), new Date('2020-10-20')); // trueContext
From 30-seconds-of-code: date-comparison
Revisions (0)
No revisions yet.