Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

怎么获取日期范围的时间序列

一个日期范围 如'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]的时间序列,这个要怎么获得


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...