DateTime comparison PHP

Viewed 3600

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";
  }

  ?>
2 Answers

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";
}

Demo

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";
}

?>
Related