Я наблюдаю очень странное поведение, когда DateTime предпочитает добавлять день, но не другие.
<?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');
?>
Кажется, это строка ->modify('last day of this month')
, которая нарушает мой код; он напечатает 1 февраля 2012 года, если я заменю первые две строки на $month_end_date = new DateTime('2011-01-31');
или
$month_end_date = new DateTime('last day of this month');
$month_end_date = new DateTime($month_end_date->format(DateTime::W3C));
или используйте мою альтернативу $event_end_date = new DateTime($month_end_date->format('Y-m-d'));
.
Имеет ли смысл, что мне нужно вызывать формат перед выполнением второй модификации?