FrengiX
FrengiX

Reputation: 77

Check for working hours

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.

Upvotes: 4

Views: 6500

Answers (2)

Kevin Lynch
Kevin Lynch

Reputation: 24733

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;
}

Upvotes: 3

thefourtheye
thefourtheye

Reputation: 239693

I believe, this should be enough

function isWorkingHour(now) {
    return now.getDay() <= 4 && now.getHours() >= 9 && now.getHours() < 17;
}

Upvotes: 6

Related Questions