1

我正在通过 PHP 构建一个日历,而我这样做的方式在某些日子里会被写两次。

我复制了这个小脚本中的行为:

<?php
//
// define a date to start from
//
$d = 26;
$m = 10;
$y = 2013;
date_default_timezone_set('CET');
$time = mktime(0, 0, 0, $m, $d, $y);

//
// calculate 10 years
//
for($i=0;$i<3650;$i++){ 
  $tomorrowTime = $time + (60 * 60 * 24);

  //
  // echo date if the next day has the same date('d') result
  //
  if(date('d',$time)==date('d',$tomorrowTime)){
    echo date('d-m-Y',$time)." was calculated twice... \n";
  }

  $time = $tomorrowTime;
}

?>

这就是我得到的:

27-10-2013 was calculated twice... 
26-10-2014 was calculated twice... 
25-10-2015 was calculated twice... 
30-10-2016 was calculated twice... 
29-10-2017 was calculated twice... 
28-10-2018 was calculated twice... 
27-10-2019 was calculated twice... 
25-10-2020 was calculated twice... 
31-10-2021 was calculated twice... 
30-10-2022 was calculated twice... 

当我定义为时$time0 (unix epoch)我没有得到相同的行为。使用有什么问题mktime()吗?还是十一月只是尴尬?

干杯,杰伦

4

3 回答 3

2

有道理,这些是闰秒。并非所有日子都需要 86400 秒。

不要使用 12 AM 进行这些计算,使用 12 PM。这会有很大帮助。

也就是说,有更好的日期计算方法。但是您在下午 12 点的数学运算适用于 UTC 时区(或 CET)。

于 2012-12-26T13:40:46.733 回答
2

此语句应更好地防止闰秒等:

$tomorrowTime = strtotime('+1 days', $time);
于 2012-12-26T13:45:04.513 回答
1

这就是为什么您不添加秒数来计算时间的原因。DST 和闰秒使得它在一天中并不总是精确的秒。60 * 60 * 24您可以使用mktime正确的计算:

for ($i = 0; $i < 3650; $i++) { 
    $time = mktime(0, 0, 0, $m, $d + $i, $y);
    //                          ^^^^^^^

    ...
}
于 2012-12-26T13:43:48.960 回答