Public
Back
Version 6
8/17/2023
type TimeSpan = {
start: Date | string;
duration: number;
};
const isInTimeSpan = (time: Date | string, timeSpan: TimeSpan): boolean => {
// Convert to date if string has been provided
if (typeof time === "string") {
time = new Date(time);
}
if (typeof timeSpan.start === "string") {
timeSpan.start = new Date(timeSpan.start);
}
// If not an array, check the single time span
// Extracting the hours, minutes, and seconds of the given time
const timeSeconds = time.getHours() * 3600 + time.getMinutes() * 60 +
time.getSeconds();
// Extracting the hours, minutes, and seconds of the time span start
const timeSpanStartSeconds = timeSpan.start.getHours() * 3600 +
timeSpan.start.getMinutes() * 60 + timeSpan.start.getSeconds();
// Calculating the end time of the time span in seconds
const timeSpanEndSeconds = timeSpanStartSeconds + timeSpan.duration * 60;
// Handling cases when time span crosses midnight
if (timeSpanEndSeconds >= 86400) {
if (
timeSeconds >= timeSpanStartSeconds ||
timeSeconds <= (timeSpanEndSeconds % 86400)
) {
return true;
}
}
else {
if (
timeSeconds >= timeSpanStartSeconds && timeSeconds <= timeSpanEndSeconds
) {
return true;
}
Updated: October 23, 2023