背景:我们的服务器PHP将时区设置为America / Los_Angeles
在工作中,我找到了这段代码
$a = 1457856000;
$b = $a + 24*3600-1;
var_dump(date('Y-m-d H:i:s', $a));
var_dump(date('Y-m-d H:i:s', $b));
输出:
string(19) "2016-03-13 00:00:00"
string(19) "2016-03-14 00:59:59"
很奇怪,但当我编码如下:
date_default_timezone_set('Etc/GMT+8');
$a = 1457856000;
$b = $a + 24*3600-1;
var_dump(date('Y-m-d H:i:s', $a));
var_dump(date('Y-m-d H:i:s', $b));
输出:
string(19) "2016-03-13 00:00:00"
string(19) "2016-03-13 23:59:59"
有人能解释为什么会这样吗?
答案 0 :(得分:6)
看一下
的输出<?php
date_default_timezone_set ('America/Los_Angeles');
$a = 1457856000;
echo date('Y-m-d H:i:s', $a), "\r\n\r\n";
for($i=0; $i<25; $i++) {
$b = $a + ($i*3600)-1;
echo date('Y-m-d H:i:s', $b), "\r\n";
}
并对daylight saving time的奇怪感到惊讶。
2016-03-13 00:59:59
2016-03-13 01:59:59
2016-03-13 03:59:59 <- and here is why you will be tired all day long next sunday
2016-03-13 04:59:59
编辑:“现在我想知道是否有任何本地PHP功能或方法,以方便格式化日期而不用担心夏令时调整?”
是的,有,见http://docs.php.net/datetime
<?php
date_default_timezone_set('America/Los_Angeles');
$a = new DateTime('2016-03-13 00:00:00');
$b = DateTimeImmutable::createFromMutable($a)->modify('1 day');
$step = new DateInterval('PT1H');
while( $a <= $b ) {
echo $a->format('Y-m-d H:i:s'), "\r\n";
$a->add($step);
}
打印
2016-03-13 00:00:00
2016-03-13 01:00:00
2016-03-13 03:00:00
2016-03-13 04:00:00
2016-03-13 05:00:00
2016-03-13 06:00:00
2016-03-13 07:00:00
2016-03-13 08:00:00
2016-03-13 09:00:00
2016-03-13 10:00:00
2016-03-13 11:00:00
2016-03-13 12:00:00
2016-03-13 13:00:00
2016-03-13 14:00:00
2016-03-13 15:00:00
2016-03-13 16:00:00
2016-03-13 17:00:00
2016-03-13 18:00:00
2016-03-13 19:00:00
2016-03-13 20:00:00
2016-03-13 21:00:00
2016-03-13 22:00:00
2016-03-13 23:00:00
2016-03-14 00:00:00
并且
date_default_timezone_set('America/Los_Angeles');
$a = new DateTime('2016-03-13 00:00:00');
$a->modify('+1 day -1 second');
echo $a->format('Y-m-d H:i:s'), "\r\n";
打印2016-03-13 23:59:59