douyou7797 2015-10-05 07:07
浏览 49
已采纳

PHP日期递增错误

I am trying to create a calendar where the date increments and each date is clickable, which links to a search. The strange part is that the date stops at 25th October, and stops incrementing. i.e 24th, 25th, 25th, 25th...

Its doesn't matter which day the calendar started with (been staring at it for a few days), but at 25th it stops incrementing.

Grateful for any advice.(The 2nd part after the gap is probably irrelevant, but including it in case there could be any link)

for ($i = 1; $i <= 30; $i++){ 
    $date = date("d-m-Y", strtotime($date) + 86400);
    array_push($array_date, $date);
    $separatedate = explode('-', $date);   
    $getday = date("l", strtotime($date));
    print "<button class='submitsearch btn' value=$array_date[$i]>" . ltrim($separatedate[0], '0') . "<br>" . $getday . "<br></button>";

    if (!checkdate($separatedate[1] , $separatedate[0]+1 , $separatedate[2])) {
        $nextmonth = date("F", strtotime($date) + 86400);
       print "<strong>". $nextmonth . "</strong><hr/>";
    }
}
  • 写回答

1条回答 默认 最新

  • doushi1473 2015-10-05 07:10
    关注

    This is the problem:

    $date = date("d-m-Y", strtotime($date) + 86400);
    

    You appear to be relying on that to increment the date. Usually, that will be fine... but it isn't when we have a 25 hour day, due to daylight saving time changes.

    I suggest you use date/time arithmetic functions (e.g. date_add) designed to add a day, rather than adding 24 hours. Or make sure all arithmetic is done in UTC, which won't have any time zone changes. In general, I would try to avoid performing any more string conversions than you really need to: keep a variable representing the date/time in an idiomatic way, and perform arithmetic on that - then just format that variable when you need to. I don't see any need to call strtotime anywhere, if you do this right.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部