PHP add 1 month to date

后端 未结 6 1352
旧巷少年郎
旧巷少年郎 2020-12-19 15:23

I\'ve a function that returns url of 1 month before.

I\'d like to display current selected month, but I cannot use simple current month, cause when user clicks link

相关标签:
6条回答
  • 2020-12-19 15:40

    simple method:

    $next_month = strtotime('august 2012 next month');
    

    better method:

    $d = new Date('August 2012');
    $next_month = $d->add(new DateInterval('P1M'));
    

    relevant docs: strtotime date dateinterval

    0 讨论(0)
  • 2020-12-19 15:40

    there are 3 options/answers

         $givendate is the given date (ex. 2016-01-20)
    
    option 1:
            $date1 = date('Y-m-d', strtotime($givendate. ' + 1 month'));
    
    option 2:
            $date2 = date('Y-m-d', strtotime($givendate. ' + 30 days'));
    
    option 3:
            $number = cal_days_in_month(CAL_GREGORIAN, date('m', strtotime($givendate)), date('Y', strtotime($givendate)));
            $date3 = date('Y-m-d', strtotime($date2. ' + '.$number.' days'));
    
    0 讨论(0)
  • 2020-12-19 15:40

    Date difference

    $date1 = '2017-01-20';
    $date2 = '2019-01-20';
    
    $ts1 = strtotime($date1);
    $ts2 = strtotime($date2);
    
    $year1 = date('Y', $ts1);
    $year2 = date('Y', $ts2);
    
    $month1 = date('m', $ts1);
    $month2 = date('m', $ts2);
    
    echo $joining_months = (($year2 - $year1) * 12) + ($month2 - $month1);
    
    0 讨论(0)
  • 2020-12-19 15:54

    Hi In Addition to their answer. I think if you just want to get the next month based on the current date here's my solution.

    $today = date("Y-m-01");
    
    $sNextMonth = (int)date("m",strtotime($today." +1 months") );
    

    Notice That i constantly define the day to 01 so that we're safe on getting the next month. if that is date("Y-m-d"); and the current day is 31 it will fail.

    Hope this helps.

    0 讨论(0)
  • 2020-12-19 15:56

    You can with the DateTime class and the DateTime::add() method:

    Documentation

    0 讨论(0)
  • 2020-12-19 16:01

    You can simple use the strtotime function on whatever input you have to arrive at April 2012 then apply the date and strtotime with an increment period of '+1 month'.

    $x = strtotime($t);
    $n = date("M Y",strtotime("+1 month",$x));
    echo $n; 
    

    Here are the relevant sections from the PHP Handbook:

    http://www.php.net/manual/en/function.date.php

    https://secure.php.net/manual/en/function.strtotime.php

    This solution solves the additional issue of incrementing any amount of time to a time value.

    0 讨论(0)
提交回复
热议问题