Many responses here rely on string-based comparisons. For accurate results, it is recommended to use numeric comparisons instead, especially when dealing with different times of the day like between 10PM and 2AM.
function checkTime(timeCheck, timeRange) {
const datePart = '2000-01-01 ', // anchoring times to the same date
d0 = new Date(datePart + timeRange[0]).getTime(),
d1 = new Date(datePart + timeRange[1]).getTime(),
dToCheck = new Date(datePart + (typeof timeCheck === 'string' ? timeCheck : timeCheck.toLocaleTimeString('en-US'))).getTime();
if (isNaN(d0) || isNaN(d1) || isNaN(dToCheck)) throw new TypeError('invalid time format');
return d0 < d1
? d0 <= dToCheck && dToCheck <= d1
: d1 <= dToCheck || dToCheck <= d0;
}
const timeRange = ['5:00:00 PM','5:59:59 PM'];
checkTime('5:15:00 PM', timeRange);
checkTime('5:15 PM', timeRange);
checkTime('5:15:00 AM', timeRange);
checkTime('5:15 AM', timeRange);
checkTime(new Date().toLocaleTimeString('en-US'), timeRange);
If you need to perform this check for multiple items, utilizing currying can enhance performance by pre-calculating the comparison range.
function buildCheckTime(startTime, endTime) {
const datePart = '2000-01-01 ',
d0 = new Date(datePart + startTime).getTime(),
d1 = new Date(datePart + endTime).getTime();
if (isNaN(d0) || isNaN(d1)) throw new TypeError('invalid time format');
return d0 < d1
? function(timeCheck) {
const dToCheck = new Date(datePart + (typeof timeCheck === 'string' ? timeCheck : timeCheck.toLocaleTimeString('en-US'))).getTime();
if (isNaN(dToCheck)) throw new TypeError('invalid time format');
return d0 <= dToCheck && dToCheck <= d1;
}
: function (timeCheck) {
const dToCheck = new Date(datePart + (typeof timeCheck === 'string' ? timeCheck : timeCheck.toLocaleTimeString('en-US'))).getTime();
if (isNaN(dToCheck)) throw new TypeError('invalid time format');
return d1 <= dToCheck || dToCheck <= d0;
}
}
const checkTime = buildCheckTime('5:00:00 PM','5:59:59 PM');
checkTime('5:15:00 PM');
checkTime('5:15 PM');
checkTime('5:15:00 AM');
checkTime('5:15 AM');
checkTime(new Date().toLocaleTimeString('en-US'));