user10535081
user10535081

Reputation:

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

  ?>

Upvotes: 3

Views: 6453

Answers (2)

John Conde
John Conde

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

Demo

Upvotes: 2

RiggsFolly
RiggsFolly

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

Related Questions