30秒学会 JavaScript 片段 · 2023年11月23日

30秒学会 JavaScript 片段 – How do I compare two dates in JavaScript?

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.

Date equality comparison

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.

代码实现

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

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

Date is before another date

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.

使用样例

const isBeforeDate = (dateA, dateB) => dateA < dateB;

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

Date is after another date

Similarly, you can use the greater than operator (>) to check if a date comes after another date.

const isAfterDate = (dateA, dateB) => dateA > dateB;

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

Date is between two dates

Combining the previous two snippets, you can check if a date is between two other dates.

const isBetweenDates = (dateStart, dateEnd, date) =>
  date > dateStart && date < dateEnd;

isBetweenDates(
  new Date('2020-10-20'),
  new Date('2020-10-30'),
  new Date('2020-10-19')
); // false
isBetweenDates(
  new Date('2020-10-20'),
  new Date('2020-10-30'),
  new Date('2020-10-25')
); // true

翻译自:https://www.30secondsofcode.org/js/s/date-comparison