PHP DateTime equality
How can I compare if two DateTime obje开发者_运维技巧cts have the same day,month and year? The problem is they have different hours/min/seconds.
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.
How about:
$date1->format('Ymd') == $date2->format('Ymd');
:wq
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 ;
}
is most useful ;)
精彩评论