2012-12-26 27 views
1

我正在通过PHP构建一个日历,并且我正在做这个结果,在一些日子里被写两次。php date('d')连续两天计算相同的输出

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

<?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()有什么问题吗? 还是11月刚刚尴尬?

干杯, 的Jeroen

+1

看起来更像是夏令时时钟可以追溯到日期比闰秒日期我 –

回答

2

这种说法应该对闰秒和后卫更好,比如:

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

谢谢!我将此标记为解决方案,因为您向我提供了优雅地解决此问题的代码。 – jeroentbt

2

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

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

也就是说,日期计算有更好的方法。但是,你的数学与12 PM将适用于UTC时区(或CET)。

+0

是!在发布这个问题后,我注意到,当我使用'$ time = mktime(1,0,0,$ m,$ d,$ y);'创建第一次时,问题没有出现。 谢谢! – jeroentbt

1

这就是为什么你不添加秒来计算时间。 DST和闰秒使它在一天内有并非总是正好是60 * 60 * 24秒。您可以使用mktime正确的计算:

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

    ... 
} 
+0

谢谢你的解释! – jeroentbt