以下代码行在两个不同的服务器 A 和 B 上返回两个不同的输出:
echo date("M Y", strtotime("2015-01"));
echo date("M Y", strtotime("2015-02"));
预期的输出是“2015 年 1 月”和“2015 年 2 月”,这在服务器 A 上是正确的。
但是服务器 B 上的相同代码返回的输出为“Jan 2015”和“Mar 2015”。
在调试时,我发现服务器 B 上的 strtotime
函数总是返回每个月当天(今天是 29 号)的时间戳,这就是为什么显示“2015-02”的原因作为“2015 年 3 月”(因为没有 2015 年 2 月 29 日)。昨天,这段代码在两台服务器上返回相同的输出,因为 2 月 28 日是有效的并且被正确地转换为 2015 年 2 月。
所以本质上,在服务器A上,有效代码是
echo date("M Y", strtotime("2015-01-01"));
echo date("M Y", strtotime("2015-02-01"));
在服务器B上,有效代码为
echo date("M Y", strtotime("2015-01-29")); //or, strtotime("2015-01-[current day]")
echo date("M Y", strtotime("2015-02-29"));
为什么这两个服务器之间存在这种差异?
最佳答案
这是不同版本的 php 的问题。 php 5.2.7 中有一个 BC,来自 documentation :
In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions.
服务器 A 的 PHP > 5.2.7,服务器 B 的 PHP < 5.2.7。
关于PHP strtotime 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30536853/