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');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…