increment date by one month

前端 未结 18 2512
广开言路
广开言路 2020-11-27 04:14

Let\'s say I have a date in the following format: 2010-12-11 (year-mon-day)

With PHP, I want to increment the date by one month, and I want the year to be automatica

18条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 04:48

    All presented solutions are not working properly.
    strtotime() and DateTime::add or DateTime::modify give sometime invalid results.
    Examples:
    - 31.08.2019 + 1 month gives 01.10.2019 instead 30.09.2019
    - 29.02.2020 + 1 year gives 01.03.2021 instead 28.02.2021
    (tested on PHP 5.5, PHP 7.3)

    Below is my function based on idea posted by Angelo that solves the problem:

    // $time - unix time or date in any format accepted by strtotime() e.g. 2020-02-29  
    // $days, $months, $years - values to add
    // returns new date in format 2021-02-28
    function addTime($time, $days, $months, $years)
    {
        // Convert unix time to date format
        if (is_numeric($time))
        $time = date('Y-m-d', $time);
    
        try
        {
            $date_time = new DateTime($time);
        }
        catch (Exception $e)
        {
            echo $e->getMessage();
            exit;
        }
    
        if ($days)
        $date_time->add(new DateInterval('P'.$days.'D'));
    
        // Preserve day number
        if ($months or $years)
        $old_day = $date_time->format('d');
    
        if ($months)
        $date_time->add(new DateInterval('P'.$months.'M'));
    
        if ($years)
        $date_time->add(new DateInterval('P'.$years.'Y'));
    
        // Patch for adding months or years    
        if ($months or $years)
        {
            $new_day = $date_time->format("d");
    
            // The day is changed - set the last day of the previous month
            if ($old_day != $new_day)
            $date_time->sub(new DateInterval('P'.$new_day.'D'));
        }
        // You can chage returned format here
        return $date_time->format('Y-m-d');
    }
    

    Usage examples:

    echo addTime('2020-02-29', 0, 0, 1); // add 1 year (result: 2021-02-28)
    echo addTime('2019-08-31', 0, 1, 0); // add 1 month (result: 2019-09-30)
    echo addTime('2019-03-15', 12, 2, 1); // add 12 days, 2 months, 1 year (result: 2019-09-30)
    

提交回复
热议问题