了解 php 中的时区本机偏移量(当 DST 未激活时)
我想为用户列出所有时区及其本地 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想出了这个函数来完成这项工作:
工作原理
该函数接受时区并创建两个
DateTime
对象:当年的 1 月 1 日 00:00和次年 1 月 1 日 00:00,均在该时区指定。然后,它计算今年的 DST 转换,并返回它找到的 DST 未激活的第一个转换的偏移量。
需要 PHP 5.3,因为使用三个参数调用
DateTimeZone::getTransitions
。如果您希望它在早期版本中工作,您将不得不接受性能损失,因为 PHP 将生成大量转换(在这种情况下,您不需要费心创建$startOfYear< /code> 和
$startOfNext
日期)。我还用不遵守 DST 的时区(例如亚洲/加尔各答)对此进行了测试,它也适用于这些时区。
测试它:
I 've come up with this function to do the job:
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: