Yang
Yang

Reputation: 8701

Comparing date with date and time, gives unexpected result

While there are a lot of posts on how to compare two dates, I couldn't find related one.

Consider this:

$x = new \DateTime('2018-08-27');
$y = new \DateTime('2018-08-28');

$interval = $x->diff($y);

$diff = $interval->d; // 1 - fine

This returns the difference between two dates - 1 day, which is expected and correct.

But for now, consider the case, when the first object has date and time in it, while the second one hasn't.

$x = new \DateTime('2018-08-27 09:33:45');
$y = new \DateTime('2018-08-28');

$interval = $x->diff($y);

$diff = $interval->d; // 0 - wrong, expecting 1

I can solve this, but I want to avoid dirty hacks and workarounds to achieve this (i.e like trimming time). Is there any native way of doing this?

Upvotes: 0

Views: 54

Answers (1)

Nick
Nick

Reputation: 147146

The problem is that new \DateTime with no time specified defaults to midnight, so there is only 14:26:15 between your two dates, which is less than one day. Hence $interval->d = 0. You will need to use setTime to ensure both times are at midnight e.g.

$interval = $x->setTime(0,0,0)->diff($y->setTime(0,0,0));

Upvotes: 2

Related Questions