dongzhang7157 2016-09-29 04:03
浏览 6
已采纳

确定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]";
}else{
    $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!

  • 写回答

1条回答 默认 最新

  • dsgdg46465 2016-09-29 04:40
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
  • ¥15 stm32的can接口不能收发数据
  • ¥15 目标检测算法移植到arm开发板
  • ¥15 利用JD51设计温度报警系统
  • ¥15 快手联盟怎么快速的跑出建立模型