本文介绍了使用Moment Js生成时隙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的对象结构
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']
我实现了自己的逻辑.但这对长度为1的breaktime数组有效;
I implemented my own logic. But that works on;y for the breaktime array of length 1.
// 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
中再添加一个数组元素,则此方法不起作用.
This doesn't work if i add one more array element to breakTime
.
推荐答案
类似的方法应该起作用:
Something like this should work:
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>
这篇关于使用Moment Js生成时隙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!