dongquweng5152 2015-06-25 09: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 09: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));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部