为什么PHP从CEST时区的时间戳返回错误的时间?

问题描述

我有一个奇怪的问题。这是我的示例代码:

<?php
// 18000 / 3600 = 5
var_dump(
    gmdate('H:i',18000),//requested time in UTC
    date('e'),//current timezone
    date('P'),//time offset in current timezone
    date('H:i',18000) //requested time in current timezone
);

这是输出:

E:\msf\www\test.php:3:string '05:00' (length=5)
E:\msf\www\test.php:3:string 'Europe/Prague' (length=13)
E:\msf\www\test.php:3:string '+02:00' (length=6)
E:\msf\www\test.php:3:string '06:00' (length=5)

5 + 2 = 6怎么可能?为什么PHP日期在特定时区返回错误的时间?

  • PHP版本7.1.24
  • 生成日期2018年11月8日05:10:41
  • 编译器MSVC14(Visual C ++ 2015)
  • x64体系结构

php.ini包含:

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone="Europe/Prague"

解决方法

您仅将unix时间戳(18000)应用于第一个和最后一个函数调用。这意味着第二次和第三次致电的结果引用的是当前日期时间(在我们所说的2020-09-09左右)。

布拉格有一个daylight saving time practice。从三月到十月,他们的时间向前移动了1个小时。也就是说,布拉格时间现在是+02:00。但是在1970年1月(时间戳18000),布拉格时间是+01:00。

要获得一致的结果,您需要对所有与日期时间相关的函数调用应用相同的时间戳:

$timestamp = 18000;

var_dump(
    gmdate('H:i',$timestamp),// requested time in UTC
    date('e',// timezone of the given timestamp
    date('P',// time offset in current timezone
    date('H:i',$timestamp) // requested time in current timezone
);

结果:

string(16) "05:00"
string(13) "Europe/Prague"
string(6) "+01:00"
string(16) "06:00

考虑时间的一些技巧:始终参考位置(例如"Europe/Prague")而不是小时数(例如"+01:00")来考虑(并存储)时区。不同的地方有不同的轮班时间做法。惯例也会随着时间而变化(例如,某个地方会占用/放弃历史记录中特定日期的DST惯例)。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...