是否有逻辑比较PHP DateTime对象的方法


Is there anyway way to logically compare PHP DateTime objects?

这是一个简单项目的一部分,该项目在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>';
}

}

除非使用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));