Madara's Ghost
Madara's Ghost

Reputation: 175007

How do I pass GMT timezones to PHP DateTime object?

The PHP DateTime object (and more specifically, the DateTimeZone object), supports many time zones. That is all nice and well, but is there a way to pass in a GMT offset as a time zone?

I know it's possible to simply add or subtract hours and apply some math, but I was wondering whether there was a built-in, robust way of doing things (or do I need to make my own abstraction layer for this).

TL;DR How can I pass GMT+N values as time zones in PHP's DateTime or DateTimeZone objects?

Upvotes: 2

Views: 368

Answers (3)

Dhiraj
Dhiraj

Reputation: 33618

You can do this using DateTime and setTimestamp

say the time format is something like this Sun, 13 May 2012 01:07:00

$currentDate = new DateTime();

$currentDate->setTimestamp(strtotime( $time.' GMT+0400'));

Note: You will have to take care of DST

Upvotes: 0

ntninja
ntninja

Reputation: 1325

You could try using the "Etc/GMT??" timezones listed at http://php.net/manual/timezones.others.php

Unfortunately these values are marked as for "backward compatible reasons" only, but you might as well use them if there isn't any other way to do this. Please note that these value do not cover :30 offsets used in some regions like Newfoundland, so you'll run into problems later on.

Another option would be to manually create an array(), mapping each timezone to a timezone name located somewhere in that area:

array(
    0 => "UTC",
    1 => "Europe/Paris",
    ...
)

Upvotes: 1

Matthew
Matthew

Reputation: 48304

You can do this:

$tz = new DateTimeZone('etc/GMT+2');

But there is this warning:

Please do not use any of the timezones listed here (besides UTC), they only exist for backward compatible reasons.

The list only supports whole hours. Some of your users may live in time zones that aren't aligned by the hour. Also note that if users select a time via a UTC offset, they will have to change it twice a year during Daylight Saving / Summer Time. Selecting by location eliminates that need.

Upvotes: 2

Related Questions