Hassan Saghir Hassan Saghir - 4 months ago 24
PHP Question

Date plus one month php

I have a small problem with dates in PHP.

When I made 31 + 1 month of January
with this code

$newDate = date('Y-m-d', strtotime('31-01-2016'.' + 1 month'));
echo $newDate;


it gives me 2 March but I need given me 29 February,

I need to add 1 month and is not 30days.

ditto for all dates:
for example
01 january + 1 month => 1 february

29 january + 1 month => 29 february

30 january + 1 month => 29 february

31 january + 1 month => 29 february

Thank for your help

Answer

As you have not accepted any of give answer , I think you are looking for this type of dates.

<?php
    $date = date('2016-01-31');
    $currentMonth = date("m",strtotime($date));
    $nextMonth = date("m",strtotime($date."+1 month"));
    if($currentMonth==$nextMonth-1){
        $nextDate = date('Y-m-d',strtotime($date." +1 month"));
    }else{
        $nextDate = date('Y-m-d', strtotime("last day of next month",strtotime($date)));
    }
    echo "Next date would be : $nextDate";
?>

Check live demo : https://eval.in/610034

  1. If date is 31-01-2016 then next date would be 29-02-2016
  2. If date is 25-01-2016 then next date would be 25-02-2016
Comments