PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Zend_Date by Example

Reviewing basic methods of Zend_Date is a good place to start for those unfamiliar with date objects in other languages or frameworks. A small example will be provided for each method below.

Output a Date

The date in a Zend_Date object may be obtained as a localized integer or string using the get() method. There are many available options, which will be explained in later sections.

Example 166. get() - Output a Date

<?php
$date 
= new Zend_Date();

// Output of the desired date
print $date->get();

Setting a Date

The set() method alters the date stored in the object, and returns the final date value as a timestamp (not an object). Again, there are many options which will be explored in later sections.

Example 167. set() - Set a Date

<?php
$date 
= new Zend_Date();

// Setting of a new time
$date->set('13:00:00',Zend_Date::TIMES);
print 
$date->get(Zend_Date::W3C);

Adding and Subtracting Dates

Adding two dates with add() usually involves adding a real date in time with an artificial timestramp representing a date part, such as 12 hours, as shown in the example below. Both add() and sub() use the same set of options as set(), which will be explained later.

Example 168. add() - Adding Dates

<?php
$date 
= new Zend_Date();

// changes $date by adding 12 hours
$date->add('12:00:00'Zend_Date::TIMES);

echo 
"Date via get() = "$date->get(Zend_Date::W3C), "\n";

// use magic __toString() method to call Zend_Date's toString()
echo "Date via toString() = "$date"\n";

Comparison of Dates

All basic Zend_Date methods can operate on entire dates contained in the objects, or can operate on date parts, such as comparing the minutes value in a date to an absolute value. For example, the current minutes in the current time may be compared with a specific number of minutes using compare(), as in the example below.

Example 169. compare() - Compare Dates

<?php
$date 
= new Zend_Date();

// Comparation of both times
if ($date->compare(10Zend_Date::MINUTE) == -1) {
    print 
"This hour is less than 10 minutes old";
} else {
    print 
"This hour is at least 10 minutes old";
}

For simple equality comparisons, use equals(), which returns a boolean.

Example 170. equals() - Identify a Date or Date Part

<?php
$date 
= new Zend_Date();

// Comparation of the two dates
if ($date->equals(10Zend_Date::HOUR)) {
    print 
"It's 10 o'clock. Time to get to work.";
} else {
    print 
"It is not 10 o'clock. You can keep sleeping.";
}

Zend Framework