PHP February: "2015-01-31" +1 month: "2015-03-30". How to fix?

If I use this code, I get strange results:

$datetime = new DateTime('2015-01-31'); $datetime->modify('+1 month'); echo $datetime->format('Ym-t') . "<br>"; $datetime->modify('+1 month'); echo $datetime->format('Ym-t') . "<br>"; $datetime->modify('+1 month'); echo $datetime->format('Ym-t') . "<br>"; 

I get this:

 2015-03-31 2015-04-30 2015-05-31 

And not 2015-02-28 .

How to fix?

+6
source share
4 answers

The DateTime method works, + 1 month increases the value of the month by one, giving you 2015-02-31 . Since February is only 28 or 29 days, this will be evaluated in the first days of March. Then, as you know, the Ymt request will give you the last day of March.

Since you already use t to get the last day of the month, you can avoid this problem starting from the date that falls at the beginning of the month:

 $datetime = new DateTime('2015-01-01'); 

Link: PHP DateTime :: change the time of adding and subtracting

+3
source

If you want to receive the last day of the next month, you can use:

 $datetime->modify('last day of next month'); 
0
source

Fix it.

 $datetime = new DateTime('2015-01-31'); $datetime->modify('28 days'); echo $datetime->format('Ym-t') . "<br>"; $datetime->modify('+1 month'); echo $datetime->format('Ym-t') . "<br>"; $datetime->modify('+1 month'); echo $datetime->format('Ym-t') . "<br>"; 

You'll get

 2015-02-28 2015-03-31 2015-04-30 
0
source

You can try this function to add months to the datetime object

  /** * * @param \DateTime $date DateTime object * @param int $monthToAdd Months to add at time */ function addMonth(\DateTime $date, $monthToAdd) { $year = $date->format('Y'); $month = $date->format('n'); $day = $date->format('d'); $year += floor($monthToAdd / 12); $monthToAdd = $monthToAdd % 12; $month += $monthToAdd; if ($month > 12) { $year ++; $month = $month % 12; if ($month === 0) { $month = 12; } } if (! checkdate($month, $day, $year)) { $newDate = \DateTime::createFromFormat('Yn-j', $year . '-' . $month . '-1'); $newDate->modify('last day of'); } else { $newDate = \DateTime::createFromFormat('Yn-d', $year . '-' . $month . '-' . $day); } $newDate->setTime($date->format('H'), $date->format('i'), $date->format('s')); return $newDate->format('Ym-d'); } echo addMonth(new \DateTime('2015-01-30'), 1); //2015-02-28 echo addMonth(new \DateTime('2015-01-30'), 2); //2015-03-30 echo addMonth(new \DateTime('2015-01-30'), 3); //2015-04-30 
0
source

Source: https://habr.com/ru/post/982064/


All Articles