Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for working hours

Tags:

javascript

I am trying to create a boolean function to check whether the current date/hour is a working hours. Now knowing that working hours are from 9AM to 5PM weekly except Fridays & Saturdays, I am facing issues with what I have come up with. I think my code works well for checking for days, but I just can't get it to work with hours as well. Here is my code:

var dayOfWeek = now.getDay();
//weekday  0==Sunday 1==Monday 2==Tuesday 3==Wednesday 4==Thurs 5==Friday 6==Sat
//Not Friday or Saturday 
if ((dayOfWeek != 5) && (dayOfWeek != 6)){

   if (now.getHours() >= 9 && now.getHours() < 17 ) {
      //Within working hours now."
   }
   else
   {
    //After working hours."
   }
}

}

Here is my HTML Code test on JSFiddle:

http://jsfiddle.net/jp9BW/ Changing my PC clock works. My test case is a working day starting 5PM. And that's when the problem happens. The else block is not hit.

like image 496
FrengiX Avatar asked Jan 13 '23 05:01

FrengiX


2 Answers

I believe, this should be enough

function isWorkingHour(now) {
    return now.getDay() <= 4 && now.getHours() >= 9 && now.getHours() < 17;
}
like image 152
thefourtheye Avatar answered Jan 22 '23 04:01

thefourtheye


I would do it like this

function checkOpeningTimes() {
    let date = new Date(); // current time
    let hours = date.getHours();
    let day = date.getDay();
    let openingDays = [ 0, 1, 2, 3, 4 ];
    return openingDays.includes( day ) && hours >= 9 && hours <= 17;
}
like image 31
Kevin Lynch Avatar answered Jan 22 '23 05:01

Kevin Lynch