I’m trying to calculate the number of hours between some arbitrary time and when the business will open (or 0 if already open). Is there a more efficientt way to do this without iterating through everything?
function calcOpen(inputDate, scheduleObj){
var d = inputDate;
var n = d.getDay();
var now = d.getHours() + "." + d.getMinutes();
var delayHours = 0;
for (let i = 0; i < 168; i++) {
d = addHours(new Date(), i);
n = d.getDay();
now = d.getHours() + "." + d.getMinutes();
day = scheduleObj[n];
if (now > day[1] && now < day[2] || now > day[3] && now < day[4]) {
delayHours = i;
break;
}
}
return addHours(new Date(), delayHours);
}
function addHours(date, hours) {
date.setHours(date.getHours() + hours);
return date;
}
var schedule = [
["Sunday", 9.30, 12.00, 15.30,22.00],
["Monday", 8.30, 12.00, 15.30,19.00],
["Tuesday", 8.30, 12.00, 15.30,19.00],
["Wednesday", 8.30, 12.00, 15.30,19.00],
["Thursday", 8.30, 12.00, 15.30,19.00],
["Friday",],
["Saturday", 8.00, 13.00]
];
var inDate = new Date();
var outdate = new Date();
outdate = calcOpen(inDate, schedule)
console.log('Input Date: ' + inDate);
console.log('Output Date: ' + outDate);
2
Answers
You can use
getTime()
method for eachDate
object and compare the values.The getTime() method of a Date instance returns the number of milliseconds for that date.
Read More
Yes, you can make it much more efficient by converting the schedule to single time slots where each slot consists of an open and close time as dates objects.
To find out if we are open or closed then becomes quite trivial 🙂
But I threw in some nice formatting for human readability and to calculate time left until close, and time left until open…
(~~ does the same thing as Math.floor() – me being lazy…)
Example output:
The code: