Check if two PHP datetime objects are set to the same date ( ignoring time )

Use the object syntax!

$firstDate = $firstDateTimeObj->format('Y-m-d');
$secondDate = $secondDateTimeObj->format('Y-m-d');

You were very close with your if expression, but the ! operator must be within the parenthesis.

if (!($firstDate == $secondDate))

This can also be expressed as

if ($firstDate != $secondDate)

My first answer was completely wrong, so I'm starting a new one.

The simplest way, as shown in other answers, is with date_format. This is almost certainly the way to go. However, there is another way that utilises the full power of the DateTime classes. Use diff to create a DateInterval instance, then check its d property: if it is 0, it is the same day.

// procedural
$diff = date_diff($firstDateTimeObj, $secondDateTimeObj);

// object-oriented
$diff = $firstDateTimeObj->diff($secondDateTimeObj);

if ($diff->format('%a') === '0') {
    // do stuff
} else {
    // do other stuff
}

Note that this is almost certainly overkill for this instance, but it might be a useful technique if you want to do more complex stuff in future.


Searching for an answer with the same problem.. I arrived to this solution that's look better for me then use diff or other things.

The main problem was ignoring the time parts of object DateTime, just set it to a time, for example at 12:00:00

$firstDateTimeObj->setTime(12, 0, 0);
$secondDateTimeObj->setTime(12, 0, 0);

// The main problem was checking if different.. but you can use any comparison
if ($firstDateTimeObj != $secondDateTimeObj) {
}