0

It's pretty easy to convert a given GMT date into local time if you're given the timezone identifier from this list in PHP: http://www.php.net/manual/en/timezones.php

For example, you can do this (where $fromTimeZone is just 'GMT', $toTimeZone is just one of the constants from that list (i.e. 'America/Chicago'), and $datetime is the GMT date):

public static function convertToTimezone($datetime, $fromTimeZone, $toTimeZone, $format = 'Y-m-d H:i')
{
    // Construct a new DateTime object from the given time, set in the original timezone
    $convertedDateTime = new DateTime($datetime, timezone_open($fromTimeZone));
    // Convert the published date to the new timezone
    $convertedDateTime->setTimezone(timezone_open($toTimeZone));
    // Return the udpated date in the format given
    return $convertedDateTime->format($format);
}

However, I'm having issue converting the same GMT date to the local time if just given the timezone offset. For instance, instead of being given 'America/Chicago', I'm given -0500 (which is the equivalent offset for that timezone).

I've tried things such as the following (where $datetime is my GMT date and $toTimeZone is the offset (-0500 in this case)):

date($format, strtotime($datetime . ' ' . $toTimeZone))

I know all the date() sort of functions are based on the servers's timezone. I just can't seem to get it to ignore that and use a timezone offset that is given explicitly.

joshholat
  • 3,371
  • 9
  • 39
  • 48
  • possible duplicate of [Javascript/PHP and timezones](http://stackoverflow.com/questions/2319451/javascript-php-and-timezones) – joshholat Apr 20 '12 at 16:36
  • You have the numeric offset. Why don't you just add or subtract the appropriate number of hours and minutes? – Celada Apr 20 '12 at 17:56

1 Answers1

0

You can convert a specific offset to a DateTimeZone:

$offset = '-0500';
$isDST = 1; // Daylight Saving 1 - on, 0 - off
$timezoneName = timezone_name_from_abbr('', intval($offset, 10) * 36, $isDST);
$timezone = new DateTimeZone($timezoneName);

Then you can use it in a DateTime constructor, e.g.

$datetime = new DateTime('2012-04-21 01:13:30', $timezone);

or with the setter:

$datetime->setTimezone($timezone);

In the latter case, if $datetime was constructed with a different timezone, the date/time will be converted to specified timezone.

Tom Imrei
  • 1,514
  • 12
  • 16