Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DateTime equality

Tags:

php

datetime

How can I compare if two DateTime objects have the same day,month and year? The problem is they have different hours/min/seconds.

like image 955
johnlemon Avatar asked May 28 '26 15:05

johnlemon


2 Answers

There's no nice way of doing that with DateTime objects. So you'll have to do, lets say, not so nice things.

$nDate1 = clone $date1;
$nDate2 = clone $date2;

//We convert both to UTC to avoid any potential problems.
$utc = new DateTimeZone('UTC');
$nDate1->setTimezone($utc);
$nDate2->setTimezone($utc);

//We get rid of the time, and just keep the date part.
$nDate1->setTime(0, 0, 0);
$nDate2->setTime(0, 0, 0);

if ($nDate1 == $nDate2) {
    //It's the same day
}

This will work, but like I said, it's not nice.

On a side note, recent experience tells me its always best to make sure both dates are on the same timezone, so I added the code for it just in case.

like image 91
Juan Avatar answered May 31 '26 04:05

Juan


How about:

$date1->format('Ymd') == $date2->format('Ymd');

:wq

like image 22
familymangreg Avatar answered May 31 '26 03:05

familymangreg



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!