使用 JavaScript 获取 2 个日期之间的所有日期

使用 JavaScript 获取 2 个日期之间的所有日期

Get all Dates between 2 Dates using JavaScript

要获取 2 个日期之间的所有日期:

  1. 创建一个将存储Date对象的数组。
  2. 遍历范围内的日期。
  3. 将每个Date对象推送到日期数组。
索引.js
function getDatesInRange(startDate, endDate) { const date = new Date(startDate.getTime()); const dates = []; while (date <= endDate) { dates.push(new Date(date)); date.setDate(date.getDate() + 1); } return dates; } const d1 = new Date('2022-01-18'); const d2 = new Date('2022-01-24'); console.log(getDatesInRange(d1, d2));

注意:上面的函数包括结果数组中的开始和结束日期。

如果您想排除结束日期,您可以将我们使用
while循环的行更改为while (date < endDate) {将小于或等于更改为小于将从结果中排除结束日期。

如果您还想排除开始日期,请改用此代码段:

索引.js
function getDatesInRange(startDate, endDate) { const date = new Date(startDate.getTime()); // ✅ Exclude start date date.setDate(date.getDate() + 1); const dates = []; // ✅ Exclude end date while (date < endDate) { dates.push(new Date(date)); date.setDate(date.getDate() + 1); } return dates; } const d1 = new Date('2022-01-18'); const d2 = new Date('2022-01-24'); console.log(getDatesInRange(d1, d2));

We manually added 1 day to exclude the start date from the results.

The getDatesInRange function takes a start and end dates as parameters and returns an array containing all of the dates between them.

We created a Date object that is a clone of startDate because the
setDate() method mutates the Date object in place and it’s not a good
practice to mutate function arguments.

The dates array is there to store all of the Date objects in the range.

We used a while loop to iterate over the dates in the range, as long as the
start date is less than or equal to the end date.

When you compare Date objects, they implicitly get converted to a timestamp of the time elapsed between the Unix Epoch (1st of January, 1970) and the given date.

setDate
方法更改给定
Date实例的月份
日期。

在每次迭代中,我们将开始日期设置为下一个日期,直到开始日期到达结束日期。

一旦开始日期到达结束日期,循环中的条件不再满足,函数返回数组。 whiledates