Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have two DateTime objects

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

Now I want to check, if those two dates are the same day, or if they are more than one day apart (but this shall also include if $lastDay is yesterday at 11pm and $today is 1 am the new day).

What I have so far is

$diff = $today->diff($lastDate);

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

The problem is: This seems to count if the dates are more than 24 hours away from each other and only sets to true if that is the case.

I could think of comparing them by comparing $date->format('d');, but this would imply that I check year and month as well. I know this would work flawlessly, but this would be a five-liner or so.

So my question is: Is there a more efficient way to check this? Any operation like diff() that gives me the result in a one-liner?

like image 701
Gottlieb Notschnabel Avatar asked Jan 13 '23 08:01

Gottlieb Notschnabel


1 Answers

Based on your latest change, wouldn't this work:

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

I agree it's kind of strange that DateTime doesn't have a method to just extract the date portion, similar to MySQL, but if you're going to use format, why not skip the diff and just compare the formatted date string for the full date of both DateTime objects?

And to simplify it further, you could use:

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

Assuming you are only using $today to confirm if $lastDate is on today.

like image 123
Anthony Avatar answered Jan 14 '23 22:01

Anthony