increment date by one month

前端 未结 18 2469
广开言路
广开言路 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:37

    I needed similar functionality, except for a monthly cycle (plus months, minus 1 day). After searching S.O. for a while, I was able to craft this plug-n-play solution:

    function add_months($months, DateTime $dateObject) 
        {
            $next = new DateTime($dateObject->format('Y-m-d'));
            $next->modify('last day of +'.$months.' month');
    
            if($dateObject->format('d') > $next->format('d')) {
                return $dateObject->diff($next);
            } else {
                return new DateInterval('P'.$months.'M');
            }
        }
    
    function endCycle($d1, $months)
        {
            $date = new DateTime($d1);
    
            // call second function to add the months
            $newDate = $date->add(add_months($months, $date));
    
            // goes back 1 day from date, remove if you want same day of month
            $newDate->sub(new DateInterval('P1D')); 
    
            //formats final date to Y-m-d form
            $dateReturned = $newDate->format('Y-m-d'); 
    
            return $dateReturned;
        }
    

    Example:

    $startDate = '2014-06-03'; // select date in Y-m-d format
    $nMonths = 1; // choose how many months you want to move ahead
    $final = endCycle($startDate, $nMonths); // output: 2014-07-02
    

提交回复
热议问题