dongquweng5152 2015-06-25 17:26
浏览 49
已采纳

有没有办法逻辑比较PHP DateTime对象?

This is part of a simple project that logs payroll hours as a datetime object in MySQL 5.5. I am trying to compare two datetime values to see if they are at least 30 minutes apart. Sounds simple enough but the value of $lastshiftend keeps being set to the same value as $mealendtime and I don't see where or how. That seems to be the only problem but there definitely could be other things I am missing. TIA.

if ($result = mysqli_query($conn, $select)) {
$row_count = mysqli_num_rows($result);
if($row_count == 1) {
    // 30 Minute Meal Break
    $lastshiftend = new DateTime($row[3]);
    $mealendtime = new DateTime('NOW');
    $mealtime = $mealendtime->diff($lastshiftend);
    $mealminend = $lastshiftend->add(new DateInterval(PT30M));
    // $mealminend = $lastshiftend->modify('+ 30 minute');

    if($mealendtime < $mealminend) {
        echo '<br>Colorado State law requires meal breaks to be at least 30 minutes in length.';
        echo '<hr><a href="./index.html">Main Menu</a>';
    } else {
        echo 'Log it!';
        // header("Location: ./ActionClockIn.php");
    }       
} else {
    echo 'Error! If you ended up here something broke!.';
    echo '<hr><a href="./index.html">Main Menu</a>';
}

}

  • 写回答

1条回答 默认 最新

  • douxiawei9318 2015-06-25 17:30
    关注

    Unless you use DateTimeImmutable() your DateTime objects will be modified when you call methods like DateTime::add() or DateTime::modify()

    $lastshiftend = new DateTimeImmutable($row[3]);
    // Now $lastshiftend is unchanged
    $mealminend = $lastshiftend->add(new DateInterval(PT30M));
    

    It looks like you will need that for both DateTime objects

    $lastshiftend = new DateTimeImmutable($row[3]);
    $mealendtime = new DateTimeImmutable(); //"NOW" is not necessary
    $mealtime = $mealendtime->diff($lastshiftend);
    $mealminend = $lastshiftend->add(new DateInterval(PT30M));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能