Get timezone offset for a given location

2019-03-20 15:55发布

Is it possible in PHP to get the timezone offset for a given location? E.g. when given the location "Sydney/Australia" to get the timezone offset as "+1100". Bonus would be for this function the keep daylight savings in mind (i.e. it's aware of daylight savings and adjusts the offset according).

3条回答
成全新的幸福
2楼-- · 2019-03-20 16:10

To display a local date/time you can use the following, where 'Europe/Berlin' would be replaced with the user's timezone.

$date = new DateTime($value);
$date->setTimezone(new DateTimeZone('Europe/Berlin'));
echo $date->format('Y-m-d H:i:s');
查看更多
霸刀☆藐视天下
3楼-- · 2019-03-20 16:23

Not sure why you need "+1100" (rather than a decimal representation) but you can use this:

$dt = new DateTime(null, new DateTimeZone('Australia/Sydney'));
$offset = $dt->getOffset()/60/60; // 11

$hours = intval($offset);
$minutes = str_pad((string)($offset - $hours) * 60, 2, '0', STR_PAD_RIGHT);
echo $hours.$minutes; // 1100

Replace null with '2010-10-01' and you'll get 1000

查看更多
乱世女痞
4楼-- · 2019-03-20 16:27

You can use the DateTimeZone class.

<?php
$timezone = new DateTimeZone("Australia/Sydney");
$offset = $timezone->getOffset(new DateTime("now")); // Offset in seconds
echo ($offset < 0 ? '-' : '+').round($offset/3600).'00'; // prints "+1100"
?>
查看更多
登录 后发表回答