PHP DateTime Equality

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

+3
source share
3 answers

There is no good way to do this with DateTime objects. So what you have to do, let's say, are not very 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 the same day
}

This will work, but, as I said, this is not nice.

On the other hand, recent experience tells me that it is always better that both dates are in the same time zone, so I added a code for this just in case.

+2
source

What about:

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

: WQ

0
source
if(date('dmY', $date1) == date('dmY', $date2))

You can put it in a function ...

function compare_dates($date1, $date2){
  if(date('dmY', $date1) == date('dmY', $date2))
    return true ;

  return false ;
}

most helpful;)

-1
source

Source: https://habr.com/ru/post/1762929/


All Articles