在 PHP 中检索当前时间时如何考虑夏令时?
当通过 PHP 脚本 (time()
) 获取时间时,在夏令时期间,它似乎返回一个相差一小时的时间值。有没有办法获得正确的时间,考虑到夏令时?
When getting the time via PHP script (time()
), during Daylight Savings Time it seems to return a time value that is one hour off. Is there any way to get the correct time, accounting for Daylight Savings Time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
time()
返回一个 Unix 时间戳,Unix 时间戳是一个固定的时间段:自 Unix 纪元以来的秒数。它不受时区的影响。一旦获得了精确的时刻,您可能想要计算给定地点的本地时间:
...将为同一时间戳打印不同的本地日期:
相同的推理适用于相反的操作:
...将打印不同的时间戳:
time()
returns a Unix timestamp and a Unix timestamp is a fixed period of time: number of seconds since the Unix Epoch. It isn't affected by time zones.Once you have the precise moment, you may want to calculate the local time in a given place:
... will print different local dates for the same timestamp:
The same reasoning applies for the opposite operation:
... will print different timestamps:
time() 获取 Unix 时间戳格式的操作系统时间。您可以使用 PHP 来纠正这个问题,但恕我直言,这应该是考虑在操作系统级别修复的问题。
time() gets the OS time in Unix Timestamp format. You could correct this with PHP but imho this should be something to consider fixing on OS level.
确保系统时间是最新的,或者在 PHP 中添加/减去: http ://www.php.net/manual/en/function.date.php#69221
Either make sure the system time is current, or add/subtract in PHP: http://www.php.net/manual/en/function.date.php#69221
使用
date_default_timezone_set()
< 设置正确的时区/a>Set correct timezone using
date_default_timezone_set()
这不是“最佳”答案,但本地服务器时间可能被您的提供商管理不当。我不知道您使用时间信息的上下文,但每当我使用此类信息时,我都会尝试使用 UTD/GMT。如果您的用户分布在世界各地,甚至是一个国家,那么纠正时间可能是一场噩梦。可以使用 UDT/GMT 合理地表示文件保存时间、日志时间或其他用途等事物。
This won't be "the" answer, but the local server time can be mismanaged by your provider. I don't know the context for your use of the time information, but whenever I use such information, I attempt to use UTD/GMT. If your users are spread out over the world, or even a single country, rectifying time can be a nightmare. Representing things, like file save times, log times, or other uses can be done reasonably with UDT/GMT.