How can I compare if two DateTime objects have the same day,month and year? The problem is they have different hours/min/seconds.
+1
A:
Casting into strings, or stripping away the hours/minutes/seconds is the only way
With strings:
if (gmdate("Ymd",$date1)==gmdate("Ymd",$date2)) {
echo "Same day";
}
With time-ints:
$lowerbound=strtotime(gmdate("Y-m-d",$date1));
// s * m * h = 86400 sec/day
if ($date2>=$lowerbound && $date2<$lowerbound+86400) {
echo "Same day";
}
[[Assuming $date1
, $date2
are int
dates in PHP- $intdate=strtotime($strdate)
to convert]]
Rudu
2010-09-02 19:35:07
+2
A:
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.
Juan
2010-09-02 19:35:11
If I apply date_default_timezone_set('GMT') would this be enough instead of $nDate1->setTimezone ?
2010-09-02 19:38:33
I believe so, as the question I had linked to just now does that.
BoltClock
2010-09-02 19:43:12
No, if for example, the DateTime had been constructed with a string of the form '2020-04-23 20:30:20+0500' the default timezone would have no effect on it, and you'd have a problem.
Juan
2010-09-02 19:45:35
Why isn't nice about this solution?
erisco
2010-09-02 19:54:09
@erisco having to clone the objects and wiping them of the time part in order to compare them just strikes me as ugly, necesary, but ugly.
Juan
2010-09-02 20:03:19
A:
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 ;)
el_quick
2010-09-02 21:08:59