背景:我们的服务器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"
谁能解释为什么会这样?
解决方法:
看看输出
<?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