如果所選時間段沖突,則我有以下串列,則回傳 true,否則回傳 false。
我試過這樣做,但它不作業
return list.some(item => {
if (new Date(item.startDate).getTime() <= new Date(selectedStartDate).getTime() && new Date(item.endDate).getTime() > new Date(selectedStartDate).getTime()) {
return true;
}
if (new Date(item.startDate).getTime() < new Date(selectedEndDate).getTime() && new Date(item.endDate).getTime() > new Date(selectedEndDate).getTime()) {
return true;
}
return false
})
const list = [
{
startDate: new Date('2022-10-10T11:00:00')
endDate: new Date('2022-10-10T11:30:00')
} ,
{
startDate: new Date('2022-10-10T12:00:00')
endDate: new Date('2022-10-10T13:00:00')
}
]
測驗1:
const selectedSlot = {
startDate: new Date('2022-10-10T10:30:00'),
endDate: new Date('2022-10-10T12:30:00')
}
測驗2:
const selectedSlot = {
startDate: new Date('2022-10-10T10:30:00'),
endDate: new Date('2022-10-10T11:30:00')
}
測驗3:
const selectedSlot = {
startDate: new Date('2022-10-11T10:30:00'),
endDate: new Date('2022-10-11T11:30:00')
}
uj5u.com熱心網友回復:
您可以分別比較 ISO 8601 日期字串。JavaScript 日期物件。如果startDate1 < endDate2 && startDate2 < endDate1. 將選定的插槽與串列中的每個元素進行比較。
function isConflict(list, {startDate: startDate2, endDate: endDate2}) {
return list.some(({startDate: startDate1, endDate: endDate1}) => startDate1 < endDate2 && startDate2 < endDate1);
}
const list = [{
startDate: new Date('2022-10-10T11:00:00'),
endDate: new Date('2022-10-10T11:30:00')
}, {
startDate: new Date('2022-10-10T12:00:00'),
endDate: new Date('2022-10-10T13:00:00')
}];
const tests = [{
startDate: new Date('2022-10-10T10:30:00'),
endDate: new Date('2022-10-10T12:30:00')
}, {
startDate: new Date('2022-10-10T10:30:00'),
endDate: new Date('2022-10-10T11:30:00')
}, {
startDate: new Date('2022-10-11T10:30:00'),
endDate: new Date('2022-10-11T11:30:00')
}];
for (const test of tests) {
console.log(isConflict(list, test));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/512538.html
標籤:javascript日期
