Calculating the difference in days between two Zend_Date objects

This just came up on #zftalk, and it appears that the information out there is either incomplete or incorrect, so I thought I’d just put out a simple solution.  Here’s a simple way to calculate the difference between two Zend_Date objects (in days):

$jan1 = new Zend_Date('1.12.2009', Zend_Date::DATES);
echo "\nJanuary first: ", $jan1->toString();
$christmas = new Zend_Date('25.12.2009', Zend_Date::DATES);
echo "\nChristmas is on: ", $christmas->toString();
$diff = $christmas->sub($jan1);
echo "\nNumber of days: ", $diff / 60 / 60 / 24;
This entry was posted in Web Development, Zend Framework and tagged , , , . Bookmark the permalink.

2 Responses to Calculating the difference in days between two Zend_Date objects

  1. Nice and simple. Just thought I’d expand on this. The sub() method returns the milliseconds difference between the receiver and the argument dates, as your example shows, but the method also is a mutator; it changes the value of the receiver date’s unix timestamp to the value that is returned. If this is a problem, you can clone the date before calling sub().

  2. This is the “classic” method to calculate the number of days but I’ve got 179.04166666667 as result for the range 15/05/2010 —> 10/11/2010! I guess there is some problem with the DST.

    I’ve resolved counting day by day in this way:

    $n_days = 0;
    for ( $i = clone $start ; $i->isEarlier( $stop ) ; $i->add( ’01′, Zend_Date::DAY ) ) {
    $n_days++;
    };

    It works, maybe :P .

blog comments powered by Disqus