Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime comparison PHP

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

  ?>

1 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

like image 109
John Conde Avatar answered May 14 '26 11:05

John Conde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!