计算时间间隔(有或没有一些库)的最佳方法是什么?
箱:
我有三个参数:
startTime
是Date
的一个实例;
endTime
Date
的实例;
interval
属于"number"
型;
将这些参数传递给某个函数,我希望有一个带有间隔日期的Date
实例数组。
例:
const startDateTime = new Date(2022, 1, 1);
startDateTime.setHours(9, 0, 0, 0);
const endDateTime = new Date(2022, 1, 1);
endDateTime.setHours(10, 30, 0, 0);
calculateDateTimeIntervals(startTime, endTime, 1800) //the last param is the time interval in seconds: 1800 is 30min
//expect array Date in time format to simplify: ['09:00', '09:30', '10:00', '10:30'];
我认为您可以使用while循环而不是计算间隔来简化代码。
const getDates = (start, end, interval) => {
const dates = [];
let date = start;
while(date <= end) {
dates.push(date);
// adjusted according to @RobG
date = new Date(date.setSeconds(date.getSeconds() + interval));
}
return dates;
}
const start = new Date(2022, 1, 1);
start.setHours(9, 0, 0, 0);
const end = new Date(2022, 1, 1);
end.setHours(10, 30, 0, 0);
const interval = 1800;
console.log(getDates(start, end, interval));
console.log(start);