Example #2 DateTimeImmutable::modify and strtotime increment or decrement individual component values
Adding +24 hours over a DST transition will add exactly 24 hours as seen in
the date/time string (unless the start or end time is on a transition
point).
Example #3 DateInterval::createFromDateString creates intervals which increment or decrement component values
DateInterval::createFromDateString() uses the
date/time parser, and the time part of the resulting interval increments
or decrements the individual component values. For an interval created
with DateInterval::__construct() the time part
covers elapsed time instead, so the two are not interchangeable when a
timezone transition falls within that time part. The date part is applied
the same way by both, so P1D and
1 day always give the same result.
To get the last day of the next month (i.e. to prevent the overflow),
the last day of format is available.
<?php
echo "Normal year:\n"; // February has 28 days
$dt = new DateTimeImmutable("2015-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("last day of next month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
echo "Leap year:\n"; // February has 29 days
$dt = new DateTimeImmutable("2016-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("last day of next month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;