I found unexpected behaviour when passing a timestamp.
timezone seems to always be GMT+0000 unless setTimezone() is set.
<?php
$MNTTZ = new DateTimeZone('America/Denver');
$ts = 1336476757;
$dt = new DateTime("@$ts", $MNTTZ);
var_dump($dt->format('T'), $dt->format('U'));
$dt->setTimezone($MNTTZ);
var_dump($dt->format('T'), $dt->format('U'));
/** Output:
string(8) "GMT+0000"
string(10) "1336476757"
string(3) "MDT"
string(10) "1336476757"
**/
?>
DateTime::setTimezone
date_timezone_set
(PHP 5 >= 5.2.0)
DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object
Opis
Styl obiektowy
Styl proceduralny
Parametry
-
object -
Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create(). Funkcja modyfikuje ten obiekt.
-
timezone -
A DateTimeZone object representing the desired time zone.
Zwracane wartości
Zwraca zmodyfikowany obiekt DateTime lub FALSE w przypadku niepowodzenia.
Rejestr zmian
| Wersja | Opis |
|---|---|
| 5.3.0 | Zmieniono zwracaną
wartość w przypadku powodzenia z NULL na DateTime. |
Przykłady
Przykład #1 DateTime::setTimeZone() example
Styl obiektowy
<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
Styl proceduralny
<?php
$date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
date_timezone_set($date, timezone_open('Pacific/Chatham'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
?>
Powyższe przykłady wyświetlą:
2000-01-01 00:00:00+12:00 2000-01-01 01:45:00+13:45
Zobacz też:
- DateTime::getTimezone() - Return time zone relative to given DateTime
- DateTimeZone::__construct() - Creates new DateTimeZone object
salladin
08-May-2012 01:59
keithm at aoeex dot com
24-Nov-2009 03:13
The timestamp value represented by the DateTime object is not modified when you set the timezone using this method. Only the timezone, and thus the resulting display formatting, is affected.
This can be seen using the following test code:
<?php
$MNTTZ = new DateTimeZone('America/Denver');
$ESTTZ = new DateTimeZone('America/New_York');
$dt = new DateTime('11/24/2009 2:00 pm', $MNTTZ);
var_dump($dt->format(DATE_RFC822), $dt->format('U'));
$dt->setTimezone($ESTTZ);
var_dump($dt->format(DATE_RFC822), $dt->format('U'));
/** Output:
string(29) "Tue, 24 Nov 09 14:00:00 -0700"
string(10) "1259096400"
string(29) "Tue, 24 Nov 09 16:00:00 -0500"
string(10) "1259096400"
**/
?>
As such, you can use this to easily convert between timezones for display purposes.
