Converting GMT time to local time using timezone offset, not timezone identifier

不羁岁月 提交于 2020-01-06 07:57:13

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/10249497/converting-gmt-time-to-local-time-using-timezone-offset-not-timezone-identifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!