8.4. Zend_Date API Overview
Пред. | Глава 8. Zend_Date | След.

## 8.4. Zend_Date API Overview

While the `Zend_Date` API remains simplistic and unitary, its design remains flexible and powerful through the rich permutations of operations and operands.

### 8.4.1. Working with Date Values

Once input has been normalized via the creation of a `Zend_Date` object, it will have an associated timezone, but an internal representation using standard UNIX timestamps . In order for a date to be rendered in a localized manner, a timezone must be known first. The default timezone is always GMT/UTC. To examine an object's timezone use `getTimeZone())`. To change an object's timezone, use `setTimeZone())`. All manipulations of these objects are assumed to be relative to this timezone.

Beware of mixing and matching operations with date parts between date objects for different timezones, which generally produce undesireable results, unless the manipulations are only related to the timestamp. Operating on `Zend_Date` objects having different timezones generally works, except as just noted, since dates are normalized to UNIX timestamps on instantiation of `Zend_Date`.

Most methods expect a constant selecting the desired `$part` of a date, such as `Zend_Date::HOUR`. These constants are valid for all of the functions below. A list of all available constants is provided in Раздел 8.5.2, «List of All Constants» . If no `$part` is specified, then `Zend_Date::TIMESTAMP` is assumed. Alternatively, a user-specified format may be used for `$part`, using the same underlying mechanism and format codes as `Zend_Locale_Format::getDate()` . If a date object is constructed using an obviously invalid date (e.g. a month number greater than 12), then `Zend_Date` will throw an exception, unless no specific date format has been selected -i.e. `$part` is either `null` or `Zend_Date::DATES` (a "loose" format).

Пример 8.8. User-specified input date format

    <?php
    $date1 = Zend_Date('Feb 31, 2007');
    echo $date1, "\n";
    $date2 = Zend_Date('Feb 31, 2007', Zend_Date::DATES);
    echo $date2, "\n";
    $date3 = Zend_Date('Feb 31, 2007', 'MM.dd.YYYY'); // strictly restricts interpretation to specified format
    echo $date3, "\n";
    ?>

If the optional `$locale` parameter is provided, then the `$locale` disambiguates the `$date` operand by replacing month and weekday names for string `$date` operands, and even parsing date strings expressed according to the conventions of that locale (see `Zend_Locale_Format::getDate()` ). The automatic normalization of localized `$date` operands of a string type occurs when `$part` is one of the `Zend_Date::DATE*` or `Zend_Date::TIME*` constants. The locale identifies which language should be used to parse month names and weekday names, if the `$date` is a string containing a date. If there is no `$date` input parameter, then the `$locale` parameter specifies the locale to use for localizing output (e.g. the date format for a string representation). Note that the `$date` input parameter might actually have a type name instead (e.g. `$hour` for `addHour()`), although that does not prevent the use of `Zend_Date` objects as arguments for that parameter. If no `$locale` was specified, then the locale of the current object is used to interpret `$date`, or select the localized format for output.

### 8.4.2. Basic `Zend_Date` Operations Common to Many Date Parts

The methods `add(), sub(), compare(), get(), and set()` operate generically on dates. In each case, the operation is performed on the date held in the instance object. The `$date` operand is required for all of these methods, except `get()`, and may be a `Zend_Date` instance object, a numeric string, or an integer. These methods assume `$date` is a timestamp, if it is not an object. However, the `$part` operand controls which logical part of the two dates are operated on, allowing operations on parts of the object's date, such as year or minute, even when `$date` contains a long form date string, such as, "December 31, 2007 23:59:59". The result of the operation changes the date in the object, except for `compare()`, and `get()`.

Пример 8.9. Operating on Parts of Dates

    <?php
    require_once 'Zend/Date.php';

    $date = new Zend_Date(); // $date's timestamp === time()

    // changes $date by adding 12 hours
    $date->add('12', Zend_Date::HOUR);
    print $date;
    ?>

Convenience methods exist for each combination of the basic operations and several common date parts as shown in the tables below. These convenience methods help us lazy programmers avoid having to type out the date part constants when using the general methods above. Conveniently, they are named by combining a prefix (name of a basic operation) with a suffix (type of date part), such as `addYear()`. In the list below, all combinations of "Date Parts" and "Basic Operations" exist. For example, the operation "add" exists for each of these date parts, including `addDay()`, `addYear()`, etc.

These convenience methods have the same equivalent functionality as the basic operation methods, but expect string and integer `$date` operands containing only the values representing the type indicated by the suffix of the convenience method. Thus, the names of these methods (e.g. "Year" or "Minute") identify the units of the `$date` operand, when `$date` is a string or integer.

#### 8.4.2.1. List of Date Parts

Таблица 8.1. Date Parts

Date Part | Explanation
--- | ---
Timestamp | UNIX timestamp, expressed in seconds elapsed since January 1st, 1970 00:00:00 GMT/UTC.
Year | Gregorian calendar year (e.g. 2006)
Month | Gregorian calendar month (1-12, localized names supported)
24 hour clock | Hours of the day (0-23) denote the hours elapsed, since the start of the day.
minute | Minutes of the hour (0-59) denote minutes elapsed, since the start of the hour.
Second | Seconds of the minute (0-59) denote the elapsed seconds, since the start of the minute.
millisecond | Milliseconds denote thousandths of a second (0-999). `Zend_Date` supports two additional methods for working with time units smaller than seconds. By default, `Zend_Date` instances use a precision defaulting to milliseconds, as seen using `getFractionalPrecision()`. To change the precision use `setFractionalPrecision($precision)`. However, precision is limited practically to microseconds, since `Zend_Date` uses `microtime()`.
Day | `Zend_Date::DAY_SHORT` is extracted from `$date` if the `$date` operand is an instance of `Zend_Date` or a numeric string. Otherwise, an attempt is made to extract the day according to the conventions documented for these constants: `Zend_Date::WEEKDAY_NARROW`, `Zend_Date::WEEKDAY_NAME`, `Zend_Date::WEEKDAY_SHORT`, `Zend_Date::WEEKDAY` (Gregorian calendar assumed)
Week | `Zend_Date::WEEK` is extracted from `$date` if the `$date` operand is an instance of `Zend_Date` or a numeric string. Otherwise an exception is raised. (Gregorian calendar assumed)
Date | `Zend_Date::DAY_MEDIUM` is extracted from `$date` if the `$date` operand is an instance of `Zend_Date`. Otherwise, an attempt is made to normalize the `$date` string into a Zend_Date::DATE_MEDIUM formatted date. The format of `Zend_Date::DAY_MEDIUM` depends on the object's locale.
Weekday | Weekdays are represented numerically as 0 (for Sunday) through 6 (for Saturday). `Zend_Date::WEEKDAY_DIGIT` is extracted from `$date`, if the `$date` operand is an instance of `Zend_Date` or a numeric string. Otherwise, an attempt is made to extract the day according to the conventions documented for these constants: `Zend_Date::WEEKDAY_NARROW`, `Zend_Date::WEEKDAY_NAME`, `Zend_Date::WEEKDAY_SHORT`, `Zend_Date::WEEKDAY` (Gregorian calendar assumed)
DayOfYear | In `Zend_Date`, the day of the year represents the number of calendar days elapsed since the start of the year (0-365). As with other units above, fractions are rounded down to the nearest whole number. (Gregorian calendar assumed)
Arpa | Arpa dates (i.e. RFC 822 formatted dates) are supported. Output uses either a "GMT" or "Local differential hours+min" format (see section 5 of RFC 822). Before PHP 5.2.2, using the DATE_RFC822 constant with PHP date functions sometimes produces incorrect results. Zend_Date's results are correct. Example: `Mon, 31 Dec 06 23:59:59 GMT`
Iso | Only complete ISO 8601 dates are supported for output. Example: `2009-02-14T00:31:30+01:00`

#### 8.4.2.2. List of Date Operations

The basic operations below can be used instead of the convenience operations for specific date parts, if the appropriate constant is used for the `$part` parameter.

Таблица 8.2. Basic Operations

Basic Operation | Explanation
--- | ---
get() | get($part = null, $locale = null) Use `get($part)` to retrieve the date `$part` of this object's date localized to `$locale` as a formatted string or integer. When using the BCMath extension, numeric strings might be returned instead of integers for large values. NOTE: Unlike `get()`, the other get*() convenience methods only return instances of `Zend_Date` containing a date representing the selected or computed date/time.
set() | set($date, $part = null, $locale = null) Sets the `$part` of the current object to the corresponding value for that part found in the input `$date` having a locale `$locale`.
add() | add($date, $part = null, $locale = null) Adds the `$part` of `$date` having a locale `$locale` to the current object's date.
sub() | sub($date, $part = null, $locale = null) Subtracts the `$part` of `$date` having a locale `$locale` from the current object's date.
copyPart() | copyPart($part, $locale = null) Returns a cloned object, with only `$part` of the object's date copied to the clone, with the clone have its locale arbitrarily set to `$locale` (if specified).
compare() | compare($date, $part = null, $locale = null) compares `$part` of `$date` to this object's timestamp, returning 0 if they are equal, 1 if this object's part was more recent than $date's part, otherwise -1.

### 8.4.3. Comparing Dates

The following basic operations do not have corresponding convenience methods for the date parts listed in Раздел 8.4, «Zend_Date API Overview» .

Таблица 8.3. Date Comparison Methods

Method | Explanation
--- | ---
equals() | equals($date, $part = null, $locale = null) returns true, if `$part` of `$date` having locale `$locale` is the same as this object's date `$part`, otherwise false
isEarlier() | isEarlier($date, $part = null, $locale = null) returns true, if `$part` of this object's date is earlier than `$part` of `$date` having a locale `$locale`
isLater() | isLater($date, $part = null, $locale = null) returns true, if `$part` of this object's date is later than `$part` of `$date` having a locale `$locale`
isToday() | isToday() Tests if today's year, month, and day match this object's date value, using this object's timezone.
isTomorrow() | isTomorrow() Tests if tomorrow's year, month, and day match this object's date value, using this object's timezone.
isYesterday() | isYesterday() Tests if yesterday's year, month, and day match this object's date value, using this object's timezone.
isLeapYear() | isLeapYear() Use `isLeapYear()` to determine if the current object is a leap year, or use Zend_Date::checkLeapYear($year) to check $year, which can be a string, integer, or instance of `Zend_Date`. Is the year a leap year?

### 8.4.4. Getting Dates and Date Parts

Several methods support retrieving values related to a `Zend_Date` instance.

Таблица 8.4. Date Output Methods

Method | Explanation
--- | ---
toString() | toString($format = null, $locale = null) Invoke directly or via the magic method `__toString()`. The `toString()` method automatically formats the date object's value according to the conventions of the object's locale, or an optionally specified `$locale`. For a list of supported format codes, see Раздел 8.5.3, «Self-Defined OUTPUT Formats» .
toValue() | toValue($part = null) Returns an integer representation of the selected date `$part` according to the conventions of the object's locale. Returns `false` when `$part` selects a non-numeric value, such as `Zend_Date::MONTH_NAME_SHORT`. NOTE: This method calls `get()` and casts the result to a PHP integer, which will give unpredictable results, if `get()` returns a numeric string containing a number too large for a PHP integer on your system. Use `get()` instead.
get() | get($part = null, $locale = null) This method returns the `$part` of object's date localized to `$locale` as a formatted string or integer. See Раздел 8.4.2.2, «List of Date Operations» for more information.
now() | now($locale = null) This convenience function is equivalent to `new Zend_Date()`. It returns the current date as a `Zend_Date` object, having `$locale`

### 8.4.5. Working with Fractions of Seconds

Several methods support retrieving values related to a `Zend_Date` instance.

Таблица 8.5. Date Output Methods

Method | Explanation
--- | ---
getFractionalPrecision() | Return the precision of the part seconds
setFractionalPrecision() | Set the precision of the part seconds

### 8.4.6. Sunrise / Sunset

Three methods provide access to geographically localized information about the Sun, including the time of sunrise and sunset.

Таблица 8.6. Miscellaneous Methods

Method | Explanation
--- | ---
getSunrise($location) | Return the date's time of sunrise
getSunset($location) | Return the date's time of sunset
getSunInfo($location) | Return an array with the date's sun dates

Пред. | Уровень выше | След.
8.3. Theory of Operation | Начало | 8.5. Constants for General Date Functions