-->

PHP的日期(“d”),计算相同的输出连续两天(php date('d') calc

2019-10-17 12:49发布

我建立通过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() 或者是十一月只是被尴尬?

欢呼声中,吉荣

Answer 1:

这种说法应该警惕更好地与闰秒和这样的:

$tomorrowTime = strtotime('+1 days', $time);


Answer 2:

有道理,这些都是闰秒。 并不是所有的天取86400秒。

不要使用12点进行这些计算,使用12点。 这将有很大的帮助。

这就是说,对于日期计算更好的方法。 但随着12点你的数学将正常工作为UTC时区(或CET)。



Answer 3:

这正是为什么你不加秒来计算时间。 DST和闰秒使其所以没有总是精确地60 * 60 * 24秒的一天。 您可以使用mktime正确的计算:

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

    ...
}


文章来源: php date('d') calculates same output for two consecutive days
标签: php date mktime