JavaScript 将日期区间转换为区间内的每个日期数组
import dayjs from "dayjs";
/**
* getDatesInRange - 将日期区间转换为区间内的每个日期数组
* @param {Date} startDate - 起始时间 例如:2024-07-25
* @param {Date} endDate - 结束时间 例如:2024-07-27
* @return {Date[]} - 数组中包含区间内的每个日期 例如:['2024-07-25','2024-07-26','2024-07-27']
*/
export function getDatesInRange(startDate:Date, endDate:Date) {
let currentDate = new Date(startDate);
let endDateTemp = new Date(endDate)
let dates = [];
// 循环直到 currentDate 大于 endDate
while (currentDate <= endDateTemp) {
dates.push(dayjs(currentDate).format('YYYY-MM-DD')); // 将日期添加到数组中
currentDate.setDate(currentDate.getDate() + 1); // 递增一天
}
return dates;
}