Issue with date when adding a month in php

Posted On: 14 Jan, 2018      Category: PHP

PHP provides many ways and functions to do manipulation with Date. But there is an issue with date while adding a month in a date when date is like 2018-03-31. 
Now, take a simple example first of adding a month.
Example 1:

<?php
$dateObj = new DateTime('2018-03-10');
$dateObj->modify('+ 1 month');
echo $dateObj->format('Y-m-d');
//Output : 2018-04-10
?>

Output of Example 1 will be 2018-04-10 and it is correct.

Now, take another example of adding a month.
Example 2:

<?php
$dateObj = new DateTime('2018-03-31');
$dateObj->modify('+ 1 month');
echo $dateObj->format('Y-m-d');
//Output : 2018-05-01
?>

Output of example 2 will be 2018-05-01 not 2018-04-30. Output gives date of month May and skips month April.  After adding 1 month, month increases by 1 and this makes the date 2018-04-31. But April month has 30 days so PHP auto-corrects by counting no of days.
 
Obtaining correct output, you need to use Date-Time stanza "last day of next month".

<?php
$dateObj = new DateTime('2018-03-31');
$dateObj->modify('last day of next month');
echo $dateObj->format('Y-m-d');
//Output : 2018-04-30
?>

Now, the correct output will be come and it will be 2018-04-30.

 

You may like: