我尝试了此操作,但由于24小时周期而无法正常工作:
const isBetweenHours = (currentHour, startHour, endHour) => {
if (currentHour >= startHour && currentHour <= endHour) {
return true
}
return false
}
有效的示例:
currentHour = 7 // 7AM
startHour = 10 // 10AM
endHour = 18 // 6PM
isBetweenHours(currentHour, startHour, endHour)
失败的示例:
currentHour = 22 // 10PM
startHour = 21 // 9PM
endHour = 4 // APM
isBetweenHours(currentHour, startHour, endHour)
答案 0 :(得分:3)
如果结束时间小于开始时间,那么我们就在第二天,因此加24以获得真实的照片:
const isBetweenHours = (currentHour, startHour, endHour) => {
if (endHour < startHour) { endHour += 24; }
if (currentHour >= startHour && currentHour <= endHour) {
return true
}
return false
}
答案 1 :(得分:1)
您的代码应能正常工作:
const isBetweenHours = (currentHour, startHour, endHour) => {
if (currentHour >= startHour && currentHour <= endHour) {
return true
}
return false
}
// example
currentHour = 7 // 7AM
startHour = 10 // 10AM
endHour = 18 // 6PM
console.log(isBetweenHours(currentHour, startHour, endHour)); // false: 7 is not between 10 and 18
currentHour = 13 // 1PM
startHour = 10 // 10AM
endHour = 18 // 6PM
console.log(isBetweenHours(currentHour, startHour, endHour)); // true: 13 is between 10 and 18
currentHour = 18 // 6PM
startHour = 10 // 10AM
endHour = 18 // 6PM
console.log(isBetweenHours(currentHour, startHour, endHour)); // true: 18 is between 10 and <=18