How to compare the date parts of two Zend_Date objects?
Asked Answered
P

1

5

I'd like to check if to Zend_Date datetimes are on the same day. How can I do that?

$date1 = new Zend_Date('2011-11-14 10:45:00');
$date2 = new Zend_Date('2011-11-14 19:15:00');
Parimutuel answered 14/11, 2011 at 11:8 Comment(3)
Same day as in, Monday, Tuesday etc... or the same date, excluding time? I any case, Zend has a compare method. framework.zend.com/manual/en/zend.date.basic.html, you can extract whatever format you want.Twentytwo
Sorry for the possible confusion, I mean the same date, excluding time, not the same day of week!Parimutuel
kind of what i figured from the example, just making sure. Also heres a list of constants you might need. framework.zend.com/manual/en/zend.date.constants.htmlTwentytwo
P
14
$date1 = new Zend_Date('2011-11-14 10:45:00');
$date2 = new Zend_Date('2011-11-14 19:15:00');
if ($date1->compareDay($date2) === 0) {
    echo 'same day';
}

Also see the chapter on Comparing Dates with Zend Date

On a sidenote, I strongly encourage you to verify if you have the need for Zend_Date. Do not use it just because it is part of ZF. Most of what Zend_Date does can be achieved faster and more comfortably with native DateTime as well:

$date1 = new DateTime('2011-11-14 10:45:00');
$date2 = new DateTime('2011-11-14 19:15:00');
if ($date1->diff($date2)->days === 0) {
    echo 'same day';
}

EDIT after comments
If you want to compare whether it's the same date just do

$date1->compareDate($date2)
Paracelsus answered 14/11, 2011 at 11:13 Comment(4)
Exactly what I was looking for (compare() and equals() can only -AFAIK- compare the day of the month, not the full date part). Thanks!Parimutuel
Sorry, I had to de-tag your answer as accepted, after noticing that it actually only compares the day, not the date (+ month + year). Same day next month returned true as well.Parimutuel
@Benjamin errrm, of course it does because you asked for the same day, not the same date. if you want the same date just do $date1->compareDate($date2)Paracelsus
My god, such an obvious method name, thanks for showing me the light! There was confusion about day vs date at the time I wrote my question, clarified in the comments. Your answer is back to Accepted ;-)Parimutuel

© 2022 - 2024 — McMap. All rights reserved.