Date comparison with Zend Date
By Bede Pavan
Added Friday 24/10/2008
Working with dates often involves some unavoidable complexity. Fortunately Zend_Date provides a simple API for some common localization issues. Unfortunately it doesn't provide the same level of support for common comparison calculations.
I've recently started playing about with the Zend_Date API to see what it offered compared with PHP's native date and time functions. Working with dates often involves some unavoidable complexity especially when considering localization and internationalization. Fortunately Zend_Date provides a simple API for handling various timezones and daylight savings, locales (such as mm/dd/yyyy vs dd/mm/yyyy), internationalization and functions for sunrise and sunset times. To get started I recommend checking out the reference guide. Don't expect a tutorial with useful working examples (something many Zend Framework components sorely need) but instead a simple reference to complement the API documentation.
Zend_Date handles the common task of comparing two dates with the compare() function. e.g.
$today = new Zend_Date();
$temp = new Zend_Date();
$tomorrow = $temp->addDay('1');
if($tomorrow->compare($today)){
echo "Tomorrow is after today. Duh!";
}
Another common task is calculating the number of days between two dates or maybe the number of years for a date of birth. Adding and subtracting dates is also very simple but may not return the results you might expect.
$today = new Zend_Date(null, 'dd/MM/YYYY');
$xmas = new Zend_Date('25/12/2007', 'dd/MM/YYYY');
$dateDiff = $today->subDate($xmas);
echo $dateDiff;
The code above will output 1 Oct 0000 00:00:00 which isn't very useful. In this case we could use the getDayOfYear() function but it won't work for differences greater than one year. What we need is the equivalent of the MySql DATE_DIFF function which returns the number of days between two dates. We could use the following as a workaround.
$diffTs = $today->get(Zend_Date::TIMESTAMP) - $xmas->get(Zend_Date::TIMESTAMP);
$tsInDays = floor((($diffTs / 60) / 60) / 24);
Obviously the number of years could be obtained by dividing the result by 365 but this might be slightly inaccurate when taking leap years into consideration. Hopefully the Zend_Date API will include a date difference function in the near future. Until then I hope this is of help.
Comments
There are no comments at this time.