Reputation:
The second block should execute but neither do. Now I'm adding another sentence so stack will let me make this edit.
<?php
$earlier_time = new DateTime('2018-12-16 11:17:30');
$thirty_seconds_later = $earlier_time->add(new DateInterval('PT' . 30 . 'S'));
if ($thirty_seconds_later < $earlier_time) {
echo "left is less than right";
} else if ($thirty_seconds_later > $earlier_time) {
echo "left is greater than right";
}
?>
Upvotes: 3
Views: 6453
Reputation: 219794
This is because when you use DateTime()
it is not immutable so when you call DateTime::add()
you change the $earlier_time
object and your comparison will always be equal (you are comparing the same object). Use DateTimeImmutable()
to solve this problem.
<?php
$earlier_time = new DateTimeImmutable('2018-12-16 11:17:30');
$thirty_seconds_later = $earlier_time->add(new DateInterval('PT' . 30 . 'S'));
if ($thirty_seconds_later < $earlier_time) {
echo "left is less than right";
} else if ($thirty_seconds_later > $earlier_time) {
echo "left is greater than right";
}
Upvotes: 2
Reputation: 94642
The problem is that you have added 30 seconds to $earlier_time
in this line
$thirty_seconds_later = $earlier_time->add(new DateInterval('PT' . 30 . 'S'));
So instead make your original datetime object immutable and it will not change its value when you do the ->add
but will set the new value into thirty_seconds_later
$earlier_time = new DateTimeImmutable('2018-12-16 11:17:30');
$thirty_seconds_later = $earlier_time->add(new DateInterval('PT' . 30 . 'S'));
if ($thirty_seconds_later < $earlier_time) {
echo "left is less than right";
} else if ($thirty_seconds_later > $earlier_time) {
echo "left is greater than right";
}
?>
Upvotes: 1