【问题标题】:Generating Time Slots using Moment Js使用 Moment Js 生成时隙
【发布时间】:2019-01-10 07:20:51
【问题描述】:

我的对象结构是这样的

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 添加一个数组元素,这将不起作用。

【问题讨论】:

  • 请在您的逻辑尝试执行的操作上添加代码 cmets。
  • 用 cmets 更新了它
  • 输出的逻辑是什么? 11:00 是休息时间,但不在输出中。 14:00 是休息时间,在输出中。 16:00 是休息时间,但不在输出中。 17:00 不是休息时间,不在输出中。 18:00 是休息时间,但 17:3018:00 在输出中。请在此处描述您的逻辑
  • breakTime ['11:00', '14:00 '],这意味着,从11:00 to 13:30,它的休息时间。 14:00 不是 break (它的结尾 break )。同样的另一个数组

标签: javascript loops momentjs timeslots


【解决方案1】:

这样的事情应该可以工作:

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);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 太好了,很高兴听到这个消息!
猜你喜欢
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
  • 2017-09-03
  • 2013-04-14
  • 2015-06-09
  • 1970-01-01
相关资源
最近更新 更多