'How can I determine what work shift the current time falls in?
I am currently getting the day of the week depending on the current date:
var d = new Date();
var day = ["Domingo","Lunes","Martes","Miercoles","Jueves","Viernes","Sabado"];
value =day[d.getDay()] ;
Now what I want to do is get the shift depending on the time of day, for example:
1st Shift = 9:00 am to 1:00 p.m
2st Shift = 1:00 p.m to 11:00 p.m
3rd Shift = 11:00 p.m to 9:00 am.
What would be the most correct way to get the turn by javascript?
Solution 1:[1]
9am = 9 hours, 1pm = 13 hours, 11pm = 21 hours, so just use a series of if statements:
let shift;
const hours = d.getHours();
if (hours >= 9 && hours < 13) {
shift = 1;
} else if (hours >= 13 && hours < 21) {
shift = 2;
} else {
shift = 3;
}
Solution 2:[2]
In certain cases, this solution is not working properly or might be I'm missing something. @Aplet123
For the following shift it's not working.
- Shift from 10:30 to 16:30
- Shift from 16:30 to 00:30
- Shift from 00:30 to 06:30
And current time is 18:30. So according to the shift details, shift 2 should be activated, but it's activating shift 3.
So my solution is to order all the shift in descending order and then compare the starting time with current time only.
shift_details = _.orderBy(shift_details, ['start_time'],['desc']);
if(moment().utc().format('HHmm') >= moment(shift_details[0].start_time).format('HHmm')){
// do something
} else if(moment().utc().format('HHmm') >= moment(shift_details[1].start_time).format('HHmm')){
// do something
} else {
// do something
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Aplet123 |
Solution 2 | Raj Patel |