victor victor - 1 year ago 72
PHP Question

Condition for specific range of time to identify Shift

I have a piece of PHP program that would supposedly identify the Shift time of a user when they login.. see below actual script condition.

$dt = new DateTime(date('H:i:s'));
$dt->setTimezone( new DateTimeZone("Asia/Manila") );
$timeNow = $dt->format('H:i:s');

if (strtotime($timeNow) >= mktime(07,0,0) && strtotime($timeNow) < mktime(15,0,0)){
$shift = "2nd [0700H - 1500H]";
}elseif(strtotime($timeNow) >= mktime(15,0,0) && strtotime($timeNow) < mktime(23,0,0)){
$shift = "3rd [1500H - 2300H]";
$shift = "1st [2300H - 0700H]";

The script above is working but there are records that falls into wrong shift.. for example a user access the page in 7:10AM which means should be in 2nd Shift but instead.. it falls into 1st Shift

I don't know what have I missed in this control flow.. so if anyone from here can help and share ideas that would be very much appreciated. Thank you!

Answer Source

There's a difference between using DateTime::setTimezone() and applying a timezone in the DateTime constructor. The former, converts the existing time to the DateTimezone specified as the argument to DateTime::setTimezone(), and the latter, assumes that the supplied formatted date is already in that timezone.

You're saying you want to know whether right now it's between 7 am and 3 pm in Manila, or between 3 pm and 11 pm, etc... So the idea is to compare only within that timezone. There is no need to do any timezone conversion here whatsoever.

$now = new DateTime("now", new DateTimeZone("Asia/Manila"));

$shift2 = new DateTime("7:00 AM", new DateTimeZone("Asia/Manila"));
$shift3 = new DateTime("3:00 PM", new DateTimeZone("Asia/Manila"));
$shift1 = new DateTime("11:00 PM", new DateTimeZone("Asia/Manila"));

if ($now >= $shift2 && $now < $shift3) {
    // It's shift 2
} elseif ($now >= $shift3 && $now < $shift1) {
    // It's shift 3
} else {
    // It's shift 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download