(PHP 5 >= 5.2.0, PHP 7, PHP 8)
DateTimeZone::__construct -- timezone_open — Creates new DateTimeZone object
Об'єктно-орієнтований стиль
Процедурний стиль
Creates a new DateTimeZone object.
A DateTimeZone object provides access to three different types of timezone
rules: UTC offset (type 1), timezone abbreviation (type
2), and timezone
identifiers as published in the IANA timezone database
(type 3).
The DateTimeZone object can be attached to DateTime and DateTimeImmutable objects to be able to render the timezone encapsulated by these objects in a local timezone.
timezoneOne of the supported timezone names, an offset value (+0200), or a timezone abbreviation (BST).
Returns DateTimeZone on success.
Процедурний стиль повертає false в разі помилки.
This method throws DateInvalidTimeZoneException if the timezone supplied is not recognised as a valid timezone. Prior to PHP 8.3, this was an Exception instead.
| Версія | Опис |
|---|---|
| 8.3.0 | Invalid values now return a DateInvalidTimeZoneException instead of a generic Exception. |
Приклад #1 Creating and attaching DateTimeZone to a DateTimeImmutable
<?php
$d = new DateTimeImmutable("2022-06-02 15:44:48 UTC");
$timezones = [ 'Europe/London', 'GMT+04:45', '-06:00', 'CEST' ];
foreach ($timezones as $tz) {
$tzo = new DateTimeZone($tz);
$local = $d->setTimezone($tzo);
echo $local->format(DateTimeInterface::RFC2822 . ' — e'), "\n";
}
?>Поданий вище приклад виведе:
Приклад #2 Catching errors when instantiating DateTimeZone
<?php
// Error handling by catching exceptions
$timezones = array('Europe/London', 'Mars/Phobos', 'Jupiter/Europa');
foreach ($timezones as $tz) {
try {
$mars = new DateTimeZone($tz);
} catch(Exception $e) {
echo $e->getMessage() . '<br />';
}
}
?>Поданий вище приклад виведе:
DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Mars/Phobos) DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Jupiter/Europa)