获取给定位置的时区偏移量

发布于 2024-09-27 04:47:19 字数 98 浏览 0 评论 0原文

PHP 是否可以获取给定位置的时区偏移量?例如,当给定位置“悉尼/澳大利亚”时,时区偏移量为“+1100”。对于此功能来说,额外的好处是记住夏令时(即它知道夏令时并据此调整偏移量)。

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).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

明媚殇 2024-10-04 04:47:19

您可以使用 DateTimeZone 类。

<?php
$timezone = new DateTimeZone("Australia/Sydney");
$offset = $timezone->getOffset(new DateTime("now")); // Offset in seconds
echo ($offset < 0 ? '-' : '+').round($offset/3600).'00'; // prints "+1100"
?>

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"
?>
浅笑轻吟梦一曲 2024-10-04 04:47:19

要显示本地日期/时间,您可以使用以下命令,其中“欧洲/柏林”将替换为用户的时区。

$date = new DateTime($value);
$date->setTimezone(new DateTimeZone('Europe/Berlin'));
echo $date->format('Y-m-d H:i:s');

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');
思慕 2024-10-04 04:47:19

不知道为什么你需要“+1100”(而不是十进制表示形式),但你可以使用这个:

$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

null 替换为 '2010-10-01' 你会获取1000

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文