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

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊