PHP time zones

Creating a date object

To convert between time zones we first need to create an object to represent the date.

$datetime = new DateTime('2011-01-31 12:01:01', new DateTimeZone('America/Los_Angeles'));

The date object above has been created and the current time zone has been set using the DateTimeZone class. The list of time zones is available on the PHP website.

For more information on date and times in PHP see the PHP date and time tutorial.

Converting the time zone

To convert the time from one time zone to another call the setTimezone method on the DateTime object.

$datetime->setTimezone(new DateTimeZone('America/New_York'));

The variable $datetime has now been converted from its original time zone America/Los_Angeles to America/New_York.

Getting the time zone

The DateTime object also has a getTimezone method to retrieve the time zone of the object.

$datetime = new DateTime('2011-01-31');
$timezone = $datetime->getTimezone();

Categories

Tags

No tags

Social