DateInterval是从2018-03-01到2018-04-01

时间:2018-02-20 11:56:16

标签: php datetime diff

我有一个带有startDate和endDate的Convention对象。我想克隆这个对象,允许选择一个新的startDate。然后,我将根据此日期位移移动子对象的所有日期。

这就是我所拥有的:

$newDate = $_POST('newDate');

$originalConventionBeginDate = clone $convention->getBeginDate();
$newConvention = clone $convention;

$jumpInterval = $originalConventionBeginDate->diff($newDate);
error_log(sprintf("Original: %s", print_r($originalConventionBeginDate, true)));
error_log(sprintf("New date: %s", print_r($newDate, true)));
error_log(print_r($jumpInterval, true));

//more code adding $jumpInterval to child objects' dates
foreach ($newConvention->getHallReservation() as $newHallR)
{
    $prevDate = clone $newHallR->getDate();
    $prevDate->add($jumpInterval);
    $newHallR->setDate($prevDate);
}

结果是,如果我克隆一个从2018-03-01开始到2018-04-01的约定,$jumpInterval 1个月和3天,那么,新的约定设置为从2018-04-01开始,其子对象设置为2018-04-04

这是我的日志信息:

  

原文:DateTime对象([日期] => 2018-03-01 00:00:00.000000 [timezone_type] => 3 [时区] =>欧洲/柏林)

     

新日期:日期时间对象([日期] => 2018-04-01 00:00:00.000000 [timezone_type] => 3 [时区] =>欧洲/柏林)

     

DateInterval对象([y] => 0 [m] => 1 [d] => 3 [h] => 0 [i] => 0 [s] => 0 [工作日] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [反转] => 0 [天] => 31 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0)

我可以看到jumpInterval也有[days] => 31,它看起来比[m] => 1 [d] => 3更准确,也许现在我们在二月这个月有28天了?

$originalConventionBeginDate$newDate的正确操作是什么?

由于

编辑:将add()位添加到代码

1 个答案:

答案 0 :(得分:-1)

我认为你应该能够通过改变来解决这个问题:

$prevDate->add($jumpInterval);

为:

$prevDate->modify("+$jumpInterval->days days");