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

时间:2015-06-25 17:26:21

标签: php mysql datetime

这是一个简单项目的一部分,它将工资核算小时记录为MySQL 5.5中的日期时间对象。我正在尝试比较两个日期时间值,看它们是否相隔至少30分钟。听起来很简单,但 $ lastshiftend 的值一直设置为与 $ mealendtime 相同的值,我不知道在哪里或如何。这似乎是唯一的问题,但肯定会有其他我想念的东西。 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 个答案:

答案 0 :(得分:1)

除非您使用DateTimeImmutable(),否则在调用DateTime::add()DateTime::modify()

等方法时,您的DateTime对象将被修改
$lastshiftend = new DateTimeImmutable($row[3]);
// Now $lastshiftend is unchanged
$mealminend = $lastshiftend->add(new DateInterval(PT30M));

看起来你将需要两个DateTime对象

$lastshiftend = new DateTimeImmutable($row[3]);
$mealendtime = new DateTimeImmutable(); //"NOW" is not necessary
$mealtime = $mealendtime->diff($lastshiftend);
$mealminend = $lastshiftend->add(new DateInterval(PT30M));
相关问题