I’ve been working a lot with the DateTime class and recently ran into what I thought was a bug when adding months. After a bit of research, it appears that it wasn’t a bug, but instead working as intended. According to the documentation found here:
Example #2 Beware when adding or
subtracting months
<?php
$date = new DateTime('2000-12-31');
$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
?>
The above example will output: 2001-01-31 2001-03-03
Can anyone justify why this isn’t considered a bug?
Furthermore does anyone have any elegant solutions to correct the issue and make it so +1 month will work as expected instead of as intended?
Why it’s not a bug:
The current behavior is correct. The following happens internally:
+1 monthincreases the month number (originally 1) by one. This makes the date2010-02-31.The second month (February) only has 28 days in 2010, so PHP auto-corrects this by just continuing to count days from February 1st. You then end up at March 3rd.
How to get what you want:
To get what you want is by: manually checking the next month. Then add the number of days next month has.
I hope you can yourself code this. I am just giving what-to-do.
PHP 5.3 way:
To obtain the correct behavior, you can use one of the PHP 5.3’s new functionality that introduces the relative time stanza
first day of. This stanza can be used in combination withnext month,fifth monthor+8 monthsto go to the first day of the specified month. Instead of+1 monthfrom what you’re doing, you can use this code to get the first day of next month like this:This script will correctly output
February. The following things happen when PHP processes thisfirst day of next monthstanza:next monthincreases the month number (originally 1) by one. This makes the date 2010-02-31.first day ofsets the day number to1, resulting in the date 2010-02-01.