了解 php 中的时区本机偏移量(当 DST 未激活时)

发布于 2024-12-03 07:04:16 字数 55 浏览 0 评论 0原文

我想为用户列出所有时区及其本地 UTC/GMT 偏移量,无论 DST

如何操作?

I want to list for the user, all timezones with their native UTC/GMT offset, regardless of DST

How can I do it?

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

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

发布评论

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

评论(1

青芜 2024-12-10 07:04:16

我想出了这个函数来完成这项工作:

function standard_tz_offset($timezone) {
    $now = new DateTime('now', $timezone);
    $year = $now->format('Y');

    $startOfYear = new DateTime('1/1/'.$year, $timezone);
    $startOfNext = new DateTime('1/1/'.($year + 1), $timezone);

    $transitions = $timezone->getTransitions($startOfYear->getTimestamp(),
                                             $startOfNext->getTimestamp());
    foreach($transitions as $transition) {
        if(!$transition['isdst']) {
            return $transition['offset'];
        }
    }

    return false;
}

工作原理

该函数接受时区并创建两个 DateTime 对象:当年的 1 月 1 日 00:00和次年 1 月 1 日 00:00,均在该时区指定。

然后,它计算今年的 DST 转换,并返回它找到的 DST 未激活的第一个转换的偏移量。

需要 PHP 5.3,因为使用三个参数调用 DateTimeZone::getTransitions。如果您希望它在早期版本中工作,您将不得不接受性能损失,因为 PHP 将生成大量转换(在这种情况下,您不需要费心创建 $startOfYear< /code> 和 $startOfNext 日期)。

我还用不遵守 DST 的时区(例如亚洲/加尔各答)对此进行了测试,它也适用于这些时区。

测试它:

$timezone = new DateTimeZone("Europe/Athens");
echo standard_tz_offset($timezone);

I 've come up with this function to do the job:

function standard_tz_offset($timezone) {
    $now = new DateTime('now', $timezone);
    $year = $now->format('Y');

    $startOfYear = new DateTime('1/1/'.$year, $timezone);
    $startOfNext = new DateTime('1/1/'.($year + 1), $timezone);

    $transitions = $timezone->getTransitions($startOfYear->getTimestamp(),
                                             $startOfNext->getTimestamp());
    foreach($transitions as $transition) {
        if(!$transition['isdst']) {
            return $transition['offset'];
        }
    }

    return false;
}

How it works

The function accepts a timezone and creates two DateTime objects: January 1st 00:00 of the current year and January 1st 00:00 of the next year, both specified in that timezone.

It then calculates the DST transitions during this year, and returns the offset for the first transition it finds where DST is not active.

PHP 5.3 is required because of the call to DateTimeZone::getTransitions with three parameters. If you want this to work in earlier versions you will have to accept a performance hit, because a whole lot of transitions will be generated by PHP (in this case, you don't need to bother with creating the $startOfYear and $startOfNext dates).

I have also tested this with timezones that do not observe DST (e.g. Asia/Calcutta) and it works for those as well.

To test it:

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