Skip to content

Instantly share code, notes, and snippets.

@NandoSangenetto
Last active March 4, 2020 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NandoSangenetto/aa7285712d998314d419a313d80c7fc3 to your computer and use it in GitHub Desktop.
Save NandoSangenetto/aa7285712d998314d419a313d80c7fc3 to your computer and use it in GitHub Desktop.
Function to valid if a specific time is between two hours, including when pass through midnight
const splitStringTime = str => str.split(":").map(str => parseInt(str, 10));
const leftZero = str => ("0" + str).slice(-2);
function isBetweenTimes({ startTime, endTime, nowTime }) {
const [hourStart, minuteStart] = splitStringTime(startTime);
const [hourEnd, minuteEnd] = splitStringTime(endTime);
const [hourNow, minuteNow] = splitStringTime(nowTime);
const startMinutes = hourStart * 60 + minuteStart;
const endMinutes =
hourEnd > hourStart
? hourEnd * 60 + minuteEnd
: hourEnd * 60 + minuteEnd + 60 * 24;
const nowMinutes =
(hourEnd > hourNow && hourStart < hourEnd) ||
(hourStart < hourNow && hourEnd < hourStart) ||
(hourEnd === hourNow && minuteEnd < minuteNow) ||
(hourEnd === hourNow && minuteEnd > minuteNow && hourStart < hourEnd) ||
(hourStart === hourNow && minuteStart <= minuteNow)
? hourNow * 60 + minuteNow
: hourNow * 60 + minuteNow + 60 * 24;
return startMinutes <= nowMinutes && nowMinutes < endMinutes;
}
const date = new Date("01/01/2020 00:00").getTime();
const limit = 60 * 24;
const perMinute = 1;
for (let i = 0; i < limit; i = i + perMinute) {
const dateNow = new Date(date + 60 * i * 1000);
const hourToTest = `${leftZero(dateNow.getHours())}:${leftZero(
dateNow.getMinutes()
)}`;
const isValid = isBetweenTimes({
startTime: "23:30",
endTime: "00:30",
nowTime: hourToTest
});
if (isValid) {
console.log(`${hourToTest} -> It's between these two hours and minutes`);
} else {
console.log(hourToTest);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment