Is this a PHP date() bug, or is there something wrong with my code?

后端 未结 2 1893
后悔当初
后悔当初 2020-12-04 02:27

I\'ve two images of an arrow, one which increments the month backward, one which increments it forward via href.

if (ISSET($_GET[\"month\"])){
    $month_in         


        
相关标签:
2条回答
  • 2020-12-04 03:11

    There is no February 29th in 2015.

    By just adding or subtracting whole months at a time, you create new dates on the same day in the requested month. In this case, you caused PHP to try and make a February 29, 2015 date. It automatically jumped forward to March 1, 2015.

    If you only care about Months, create dates on the first of each month:

    date("F y", mktime(0,0,0, $month_index, 1, 2015));
    

    Good thing you are writing this code and caught the bug today, or you would have had a bug that only appeared on the 29th (or 31st) of every month (except leap years)!

    Dates are hard.

    0 讨论(0)
  • 2020-12-04 03:18

    It's how dates work and when you encounter February and the 29th day of the month or later. When you add a month to a date after the last day of February of that year (i.e. 28th of February this year) you will skip over February. Whenever iterating through months you should always work with the start of the month to avoid February being skipped. So if you start with January 30th and add "one month" since there is no Feb 30th you will skip ahead to March.

    Here's how you can iterate through months without knowing how many days are in February (or caring). I picked an arbitrary end date of one year from now.

    $start    = new DateTimeImmutable('@'.mktime(0, 0, 0, $month_index, 1, 2014));
    $end      = $start->modify('+1 year')
    $interval = new DateInterval('P1M');
    $period   = new DatePeriod($start, $interval, $end);
    
    foreach ($period as $dt) {
        echo $dt->format('F Y');
    }
    
    0 讨论(0)
提交回复
热议问题