1

When i have current date is in "31/12/2017". I need to find date of after 2 months that means its February. When its february i need to get as "29/2/2018". But When we use below code i got "03/03/2018". Can you please help me to solve this task,

Here i added my PHP code,

$xmasDay = new DateTime('2017-12-31 + 2 month');
echo $xmasDay->format('Y-m-d');
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
  • Quick answer: There is no 29-30-31/2/2018, so PHP shifts to 3/3/2018. You can find the answer here: https://stackoverflow.com/questions/3602405/php-datetimemodify-adding-and-subtracting-months – Tuan Duong Sep 20 '17 at 05:36

2 Answers2

0

please try this

 <?php

 function add_month($date_str, $months)
 {
     $date = new DateTime($date_str);

     // We extract the day of the month as $start_day
     $start_day = $date->format('j');

    // We add 1 month to the given date
     $date->modify("+{$months} month");

    // We extract the day of the month again so we can compare
    $end_day = $date->format('j');

   if ($start_day != $end_day)
   {
        // The day of the month isn't the same anymore, so we correct the date
       $date->modify('last day of last month');
   }

   return $date->format('Y-m-d');
}
$result = add_month('2017-12-31', 2);
echo $result
Pritamkumar
  • 682
  • 1
  • 11
  • 30
0

calculate from first of the month, then use date t

$orginal = '2017-12-31';
$orginal = explode('-', $orginal);

$originalDate = strtotime($orginal[0] . '-' .  $orginal[1] . '-01 00:00:00');
$newDate      = strtotime('+2 month', $originalDate);

echo date('Y-m-t', $newDate);
// or
$date = new DateTime();
$date->setTimestamp($newDate);
echo $date->format('Y-m-t');
Ryan Harne
  • 469
  • 3
  • 7