How can I effectively compare two DateTimes and check if they are on the same day?

I have two DateTime objects

 $lastDate = $entity->getDate(); // is a DateTime with same format as $today $today = \DateTime::createFromFormat('!Ym-d', date('Ym-d')); 

Now I want to check whether these two dates will be on the same day or if they are more than one day $lastDay (but this will also include if $lastDay at 11 p.m. yesterday and $today is 1 a.m. day).

What am i still

 $diff = $today->diff($lastDate); if($diff->days > 0) { $return = false; } else { $return = true; } 

The problem is that it seems to be considered if the dates are more than 24 hours apart and only sets to true , if so.

I could think of comparing them by comparing $date->format('d'); but that will mean that I check the year and month. I know this will work flawlessly, but it will be five-line or so.

So my question is: is there a more efficient way to test this? Any operation like diff() that gives me the result in a single line sheet?

+4
source share
1 answer

Based on your recent changes, will this not work:

 $votedToday = ($today->format('Ym-d') == $lastDate->format('Ym-d')); 

I agree that DateTime does not have a method to simply retrieve a part of the date similar to MySQL, but if you are going to use format , why not skip diff and just compare the formatted date string for the full date of both DateTime objects?

To simplify it, you can use:

 $votedToday = ($lastDate->format('Ym-d') == date('Ym-d')); 

Assuming you are using $today to confirm if $lastDate .

+8
source

All Articles