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.1.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;

Related posts:

  1. 30 Days with Occam’s Protocol Over the last couple of years I’ve experimented with a...
This entry was posted in Web Development, Zend Framework and tagged , , , . Bookmark the permalink.
  • http://www.lampdigital.com Michael Hodgins

    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().

  • http://www.xoen.org Aldo “xoen” Giambelluca

    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 .

    • Greg

      It returns the number of days as a real number, in which the decimals represent de haurs, minutes, seconds and milliseconds. You can even set the time to 00:00:00.0000 or floor your result. It is in my opinion way more simple than 179+ clones of a Zend_Date object followed by a day addition.

      Greg

  • http://www.facebook.com/mrbush Scott Bush

    Just an observation: shouldn’t your $jan1 variable be 1.1.2009 not 1.12.2009?

    • http://cmorrell.com Chris Morrell

      Good point! Fixed.

  • David Mintz

    I tried your snippet and got  PHP Notice:  Object of class Zend_Date could not be converted to int and a very wrong result.

    I changed your last line to 

        echo “nNumber of days: “, $diff->toValue() / 60 / 60 / 24;

    Ding!