Klass DateTimeZone
Klassen DateTimeZone låter dig arbeta med tidszoner i PHP.
Tar i konstruktorn en sträng med en tidszonsidentifierare.
Syntax
new DateTimeZone(string $timezone);
Exempel
Skapar ett tidszonsobjekt för Moskva:
<?php
$timezone = new DateTimeZone('Europe/Moscow');
print_r($timezone);
?>
Resultat av kodkörning:
DateTimeZone Object
(
'timezone_type' => 3
'timezone' => Europe/Moscow
)
Exempel
Användning med klassen DateTime:
<?php
$timezone = new DateTimeZone('America/New_York');
$date = new DateTime('now', $timezone);
echo $date->format('Y-m-d H:i:s');
?>
Resultat av kodkörning (nuvarande tid i New York):
'2025-06-15 14:30:00'
Exempel
Hämta lista över alla tillgängliga tidszoner:
<?php
$timezones = DateTimeZone::listIdentifiers();
print_r(array_slice($timezones, 0, 5));
?>
Resultat av kodkörning:
[
'Africa/Abidjan'
'Africa/Accra'
'Africa/Addis_Ababa'
'Africa/Algiers'
'Africa/Asmara'
]
Exempel
Hämta tidszonens förskjutning från UTC:
<?php
$timezone = new DateTimeZone('Asia/Tokyo');
echo $timezone->getOffset($date) / 3600;
?>
Resultat av kodkörning:
9
Se även
-
klassen
DateTime,
för att arbeta med datum och tid -
klassen
DateInterval,
som anger ett tidsintervall -
funktionen
date_default_timezone_set,
för att ställa in standardtidszon