我看到很奇怪的行为,与DateTime选择有时添加一天,而不是其他人。PHP的日期时间跳过添加
<?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')
线,它打破了我的代码;它会打印2012年2月1日,如果我有$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'));
。
是否有意义,我需要在进行第二次修改之前调用格式?
“行不通” 是发生了什么事的一个很模糊的描述。你能提供更多细节吗? – 2012-01-09 10:42:55
我修改了我的帖子:破码输出2012-01-31,当它应该给2012-02-01。 – PeterB 2012-01-09 11:01:35