一个日期范围 如'2020-12-11' 到 '2020-12-16' 要获取一个格式为[2020-12-11 00:00 ~ 00:59, 2020-12-11 01:00 ~ 01:59...., 2020-12-16 23:00 ~ 23:59]的时间序列,这个要怎么获得
function zeroPrefix(value) {
return (value + '').padStart(2, '0');
}
function dateTimeListBuilder(startTime, endTime) {
const [startYear, startMonth, startDate] = startTime.split('-');
const [endYear, endMonth, endDate] = endTime.split('-');
const startTimestamp = new Date(startYear, startMonth - 1, startDate).getTime();
const endTimestamp = new Date(endYear, endMonth - 1, endDate, 23, 59, 59).getTime();
if (startTimestamp > endTimestamp) {
alert('开始时间应小于结束时间');
return;
}
const result = [];
const mapper = new Array(24).fill(0);
for (let i = startTimestamp, j = 0; i <= endTimestamp; i += 86400000, j++) {
const currentDate = new Date(startYear, startMonth - 1, +startDate + j);
result.push(
...mapper.map((_, index) => {
index = zeroPrefix(index);
return `${currentDate.getFullYear()}-${zeroPrefix(currentDate.getMonth() + 1)}-${zeroPrefix(currentDate.getDate())} ${index}:00-${index}:59`;
})
);
}
return result;
}
dateTimeListBuilder('2020-12-11', '2020-12-16');
// 甚至可以这么传参
dateTimeListBuilder('2020-13-1', '2021-1-5');