gpt4 book ai didi

javascript - 使用 Moment Js 生成时间段

转载 作者:行者123 更新时间:2023-12-03 00:25:14 29 4
gpt4 key购买 nike

我的对象结构如下

var x = {
nextSlot: 30,
breakTime: [
['11:00', '14:00'], ['16:00', '18:00']
],
startTime: '8:00',
endTime: '20:00'
}

我想生成从 startTime 到 endTime 的时间段。但我不想考虑时间段中的breakTime。输出应该是

['08:00','08:30','09:00','09:30','10:00','10:30','14:00','14:30','15:00','15:30', '17:30', '18:00', '18:30','19:00','19:30']

我实现了自己的逻辑。但这适用于;y 对于长度为 1 的breaktime 数组。

// Check whether the startTime is less than endTime
while (moment(x.startTime, ['HH:mm']).format('HH:mm') < moment(x.endTime, ['HH:mm']).format('HH:mm')) {
for (let i = 0; i < x.breakTime.length; i++) {
// if startTime is greater then breakTime[i][0], and if starttime is less then breaktime[i][1],
//just add nextSlot to starttime
if (moment(x.startTime, ['HH:mm']).format('HH:mm') >= moment(x.breakTime[i][0], ['HH:mm']).format('HH:mm') && moment(x.startTime, ['HH:mm']).format('HH:mm') < moment(x.breakTime[i][1], ['HH:mm']).format('HH:mm')) {
x.startTime = moment(x.startTime, ['HH:mm']).add(x.nextSlot, 'm').format('HH:mm');
} else {
//otherwise, push the time to slot array and then increment it by nextSlot
slots.push(moment(x.startTime, ['HH:mm']).format('hh:mm'));
x.startTime = moment(x.startTime, ['HH:mm']).add(x.nextSlot, 'm').format('HH:mm');
}
}
}

如果我向 breakTime 添加一个数组元素,这将不起作用。

最佳答案

这样的事情应该有效:

var x = {
nextSlot: 30,
breakTime: [
['11:00', '14:00'], ['16:00', '18:00']
],
startTime: '8:00',
endTime: '20:00'
};

var slotTime = moment(x.startTime, "HH:mm");
var endTime = moment(x.endTime, "HH:mm");

function isInBreak(slotTime, breakTimes) {
return breakTimes.some((br) => {
return slotTime >= moment(br[0], "HH:mm") && slotTime < moment(br[1], "HH:mm");
});
}

let times = [];
while (slotTime < endTime)
{
if (!isInBreak(slotTime, x.breakTime)) {
times.push(slotTime.format("HH:mm"));
}
slotTime = slotTime.add(x.nextSlot, 'minutes');
}

console.log("Time slots: ", times);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>

关于javascript - 使用 Moment Js 生成时间段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54123653/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com