Reputation: 141
i've code like this, but always return value 'Shift 2'.
$now = 6;
$string = '09:00 - 14:00,14:00 - 09:00';
$activeHour = explode(",", $string);
foreach ($activeHour as $key => $value) {
$activeHours = explode('-',$value);
$start = explode(':',$activeHours[0]);
$end = explode(':',$activeHours[1]);
if( $now >= (int)$start[0] && $now <= (int)$end[0] ){
$status = "Shit 1";
}else{
$status = "Shift 2";
}
}
How to make result with this condition? $shift1 = 09:00 - 14:00; ==> Shift 1 $shift2 = 14:00 - 09:00; if $now time between $shift1 show result "Shift 1" and if $now between $shift2 show with result "Shift 2"
Upvotes: 0
Views: 36
Reputation: 147206
You can use this function (which uses strtotime
to generate values which can be compared directly) to figure out which shift you are in. Note that it is capable of dealing with multiple shift definitions, which don't necessarily cover the whole day:
function get_shift($now, $string) {
$now = strtotime($now);
foreach (explode(",", $string) as $shift => $shiftHours) {
list($start, $end) = explode('-', $shiftHours);
$stime = strtotime($start);
$etime = strtotime($end);
if ($etime < $stime && ($now < $etime || $now >= $stime) || $now >= $stime && $now < $etime) {
return "Shift " . ($shift+1);
}
}
return "Outside hours";
}
Sample usage:
for ($now = 0; $now < 24; $now++) {
echo "$now: " . get_shift("$now:00", '09:00 - 14:00,16:00 - 21:00, 23:00 - 07:00') . "\n";
}
Output:
0: Shift 3
1: Shift 3
2: Shift 3
3: Shift 3
4: Shift 3
5: Shift 3
6: Shift 3
7: Outside hours
8: Outside hours
9: Shift 1
10: Shift 1
11: Shift 1
12: Shift 1
13: Shift 1
14: Outside hours
15: Outside hours
16: Shift 2
17: Shift 2
18: Shift 2
19: Shift 2
20: Shift 2
21: Outside hours
22: Outside hours
23: Shift 3
Upvotes: 1