I am seeing very strange behaviour, with DateTime choosing to add a day sometimes, but not others.
<?php
// If you're running this after Jan 2012, use: new DateTime(date('Y-m-d', strtotime('2012-01-09')));
$month_end_date = new DateTime();
$month_end_date->modify('last day of this month');
$event_end_date = new DateTime('2012-03-15');
if ($event_end_date > $month_end_date) {
// Using this line a day is never added on below and the date stays as 31 Jan 2012
$event_end_date = clone $month_end_date;
// This line allows the ->add() call to work, and gives 1 Feb 2012 as output:
#$event_end_date = new DateTime($month_end_date->format('Y-m-d'));
}
$event_end_date->add(new DateInterval('P1D'));
// Date should now be 1st Feb
echo "Should be 1 Feb: ". $event_end_date->format('Y-m-d');
?>
It appears to be the ->modify('last day of this month') line which breaks my code; it will print 1 Feb 2012 if I replace the first two lines with $month_end_date = new DateTime('2011-01-31'); or
$month_end_date = new DateTime('last day of this month');
$month_end_date = new DateTime($month_end_date->format(DateTime::W3C));
or use my alternative $event_end_date = new DateTime($month_end_date->format('Y-m-d'));.
Does it make sense that I need to call format before making a second modification?
It appears the usage of “first” or “last” directly in the constructor of the DateTime object causes it to become immutable. This does seem like a bug.
e.g.
Results in: