php how do I add calendar months to a date?

Actually, I have this code here:

$date_do_test = date_create($date3);
            $date_do_new = date_modify($date_do_test, $diff.'month');

            $data_all = date_format($date_do_new, 'd.m.Y');

            if ($diff==0) {
            echo "0";
            } else {
            echo date_format($date_do_new, 'd.m.Y');

            }

It works quite well from the part if the numbers of the month are from 1 to 30. But if the month has 31 days, then for example, if you add THREE months to 31.03.18, it outputs 01.07.18 instead of 30.06.18.

Please tell me how this can be fixed?

Author: scanread, 2018-06-04

3 answers

This is how to correctly calculate any increment to the date.

$day = date('d.m.Y', mktime(0, 0, 0, date("m") + 1, date("d") + 42, date("Y")));

The mktime() function will do everything by itself.

 1
Author: MAX, 2018-06-05 08:26:37
<?php

$time = strtotime("now");
$timenow = date("Y-m-d", $time); // 2018-06-04
$newdate = date("Y-m-d", strtotime("+1 month", $time)); // 2018-07-04
$newdate1 = date("Y-m-d", strtotime("+2 month", $time)); // 2018-08-04
$newdate2 = date("Y-m-d", strtotime("+3 month", $time)); // 2018-09-04

$diff = 3;
$date_do_test = date_create("2018-07-04");
$date_do_new = date("Y-m-d", strtotime("+".$diff." month", strtotime(date_format($date_do_test, 'Y/m/d'))));
if ($diff==0) 
    echo "0";
else 
    echo $date_do_new; // 2018-10-04

You can do it like this

<?php

$diff = 3;
$date_do_test = strtotime("2018/03/31");
$date_do_new = function() use ($date_do_test, $diff) {
    $temp = date("t", $date_do_test) == 31 ? 86400 : 0;
    return strtotime("+".$diff." month", $date_do_test) - $temp;
};

$date_do_format = date("Y-m-d", $date_do_new());
if ($diff==0) 
    echo "0";
else 
    echo $date_do_format; // 2018-06-30

As for your problem, this was discussed gist-github

That behavior is perfectly expected when moving 1 month back/ahead from a 31-days month over 30-days month.

That is, 1 day plus a month, for this purpose, we delete one day in the function if 31 days

$temp = date("t", $date_do_test) == 31 ? 86400 : 0;

date("t", $date_do_test) - number of days in a month

 1
Author: Dima Kaukin, 2018-06-05 16:18:52
$diff=3;
function add_month($time, $num=1) { 
    $d=date('j',$time);  // день 
    $m=date('n',$time);  // месяц 
    $y=date('Y',$time);  // год 
  global $diff;
    $num = $diff;

    $m+=$num; 
    if ($m>12) { 
        $y+=floor($m/12); 
        $m=($m%12); 

        if (!$m) { 
            $m=12; 
            $y--; 
        } 
    } 


    if ($d==date('t',$time)) { 
        $d=31; 
    } 

    while(true) { 
        if (checkdate($m,$d,$y)){ 
            break; 
        } 
        $d--; 
    } 

    return mktime(0,0,0,$m,$d,$y); 
} 
echo date('d.m.Y',add_month(strtotime('2015-03-31')));

I used a global variable, because it all depends on how many months to add, $diff=3; and voila. The question is closed.

 0
Author: scanread, 2018-06-05 06:24:39