我试图获得可用插槽的时间。我的数据库中有startDateTime
,endDateTime
,duration
和bufferBetweenSlots
字段。通过一些计算,我已经算出了可用插槽的数量。
字段的值为:
startDateTime: 8/20/2021 11:30 AM
endDateTime: 8/20/2021 9:30 PM
duration: 60
bufferBetweenSlots: 30
但是我不确定如何获得可用插槽的开始和结束时间。例:10:00 - 11:00
const getTimeDiffInMins = (endTime, startTime) =>
(+new Date(endTime) - +new Date(startTime)) / (60 * 1000);
const getMultipleTimeSlots = (data) => {
const diff = getTimeDiffInMins(data.end_date_time, data.start_date_time);
const totalSlots = diff / data.duration;
const totalBuffer = data.buffer_between_slots * totalSlots;
const availableSlots = (diff - totalBuffer) / 60;
return availableSlots;
};
有什么建议吗?
您应该只需要在插槽之间使用一个缓冲区,因此缓冲区的数量要比插槽的数量少1,即您想要解决:
n * slotTime + (n - 1) * bufferTime == totalTime
这样:
totalTime <= diff
您可以通过将缓冲区添加到totalTime并除以slotTime + bufferTime
,然后将结果加成以获得可用插槽加上缓冲区的总数来实现这一点。然后,您可以迭代生成所需的开始和结束时间。例如
let startDateTime = new Date(2021,7,8,11,30); // 20 Aug 2021 11:30
let endDateTime = new Date(2021,7,8,22); // 20 Aug 2021 22:00
let duration = 60; // minutes
let bufferBetweenSlots = 30; // minutes
let diff = (endDateTime - startDateTime) / 6e4; // minutes
let numberOfSlots = Math.floor((diff + bufferBetweenSlots) / (duration + bufferBetweenSlots)); // minutes
let slots = [];
let time = new Date(startDateTime);
for (let i = 0; i < numberOfSlots; i++) {
// Add the slot start time
slots[i] = {start: time.toString()};
// Increment time to end of slot
time.setMinutes(time.getMinutes() + duration);
// Add the end time
slots[i].end = time.toString();
// Increment time to end of buffer
time.setMinutes(time.getMinutes() + bufferBetweenSlots);
}
console.log(slots);
我将结束时间更改为22:00,以显示它只放入满槽。是否将时间戳或日期对象推入插槽数组取决于您。只要记住,如果添加日期,要像这样复制日期:
slots[i] = {start: new Date(+time)};
...
slots[i].end = new Date(+time);
感谢@RobG花时间回答。以下是我解决这个问题的方法。
const getTimeDiffInMins = (endTime, startTime) =>
(+new Date(endTime) - +new Date(startTime)) / (60 * 1000);
const convertToMilliSecs = (value) => value * 60 * 1000;
// coming from the db
const data = {
duration: 60,
buffer_between_slots: 30,
start_date_time: '2021-08-20T10:30:00Z',
end_date_time: '2021-08-20T20:30:00Z',
};
const {
duration: a,
buffer_between_slots: b,
end_date_time: x,
start_date_time: y,
} = data;
const duration = getTimeDiffInMins(x, y);
const slotDuration = a;
const totalSlots = a + b;
const numberOfSlots = Math.floor(duration / totalSlots);
const slotsAvailable = [...Array(numberOfSlots).keys()].map((slotNumber) => {
const slotStart = (slotNumber - 1) * totalSlots;
const slotEnd = slotStart + slotDuration;
return {
start: +new Date(y) + convertToMilliSecs(slotStart),
end: +new Date(y) + convertToMilliSecs(slotEnd),
};
});
/*
Now we can format the time however we want
I'm using momentjs:
moment(new Date(slot.start)).format('h:mma')
*/
console.log(slotsAvailable);