使用DateInterval向DateTime添加月份会更改原始日期以匹配新日期 [英] Adding months to DateTime with DateInterval changes original date to match new date
问题描述
我有一个非常简单的代码:
I have this pretty simple code:
$start_date = new DateTime($post['start_date']);
$end_date = $start_date->add(new DateInterval('P6M'));
echo $start_date->getTimestamp(); // 1351836000
echo $end_date->getTimestamp(); // 1351836000
当然,两者都以相同的时间戳结束,因为添加日期间隔会影响原始时间戳$ start_date。那么我该怎么做,这样我才能保留原始的$ start_date并在另一个变量中添加6个月?
Of course, both end up as the same timestamp because adding the date interval affects the original $start_date. So how do I go about this so I can keep the original $start_date yet add 6 months to it in another variable?
我没有运气尝试过这个
I tried this with no luck:
$start_date = new DateTime($post['start_date']);
$start_date_actual = $start_date;
$end_date = $start_date_actual->add(new DateInterval('P6M'))->getTimestamp();
推荐答案
变量保存对对象的引用,而不是对对象本身的引用。因此,赋值只会使您获得更多指向同一对象的变量,而不是该对象的多个副本。
Variables hold references to objects, not the objects themselves. So assignment just gets you more variables pointing to the same object, not multiple copies of the object.
如果您想要,请使用 clone
关键字:
If you want a copy, use the clone
keyword:
$end_date = clone $start_date;
$end_date->add(new DateInterval('P6M'));
这篇关于使用DateInterval向DateTime添加月份会更改原始日期以匹配新日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!