我有一个类似的问题,我有一个人的繁忙时段,并且想找到那个人可用的时段(“空闲”)。这是我编码的,希望它可以帮助某人:
function getFreeOfDay (date, busySlots) {
function sameDateDifferentTime(date, hours, minutes) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), hours, minutes, 0, 0);
}
// Define the range for free spots
var freeSlots = date.getDay() === 0 || date.getDay() === 6 ? [] : [
{
start: sameDateDifferentTime(date, 10, 0), // 10:00 (AM)
end: sameDateDifferentTime(date, 12, 30), // 12:30 (AM)
},
{
start: sameDateDifferentTime(date, 13, 30), // 13:30 (AM)
end: sameDateDifferentTime(date, 19, 0), // 19:00 (AM)
}
];
// Go through the busy slots, to remove them from the free spots
busySlots.forEach(function (busySlot) {
freeSlots.forEach(function (freeSlot, freeSlotIndex) {
if (busySlot.end <= freeSlot.start || busySlot.start >= freeSlot.end) {
// Do nothing, the busy slot doesn't interfere with the free slot
}
else if (busySlot.start <= freeSlot.start && busySlot.end >= freeSlot.end) {
// The free slot is in the middle of the busy slot, meaning it's not possible to plan anything in there
freeSlots.splice(freeSlotIndex, 1);
}
else if (busySlot.start < freeSlot.start && busySlot.end > freeSlot.start) {
// The busy slot overlaps with the free slot, it ends after the start of the free slot
freeSlots[freeSlotIndex] = {
start: busySlot.end,
end: freeSlot.end
};
}
else if (busySlot.start < freeSlot.end && busySlot.end > freeSlot.end) {
// The busy slot overlaps with the free slot, it starts before the end of the free slot
freeSlots[freeSlotIndex] = {
start: freeSlot.start,
end: busySlot.start
};
}
else {
// Then the busy slot is in the middle of a free slot
freeSlots[freeSlotIndex] = {
start: freeSlot.start,
end: busySlot.start
};
freeSlots.splice(freeSlotIndex + 1, 0, {
start: busySlot.end,
end: freeSlot.end
});
}
});
});
// Remove empty free slots
freeSlots.forEach(function (freeSlot, freeSlotIndex) {
if (freeSlot.start >= freeSlot.end) {
freeSlots.splice(freeSlotIndex, 1);
}
});
return freeSlots;