首页 > 解决方案 > 如何计算两个 DateInterval 对象的总和

问题描述

我有两个日期间隔对象,有没有添加这些间隔对象的默认方法?

$date1 = date_create("2013-03-15");
$date2 = date_create("2013-12-12");
$diff_1=date_diff($date1,$date2);
echo $diff_1->format("%y years").' '.$diff_1->format("%m months"). ' ' . $diff_1->format("%d days");
//0 years 8 months 27 days

$date3 = date_create("2015-02-15");
$date4 = date_create("2015-12-12");
$diff_2=date_diff($date3,$date4);
echo $diff_2->format("%y years").' '.$diff_2->format("%m months"). ' ' . $diff_2->format("%d days");
//0 years 9 months 27 days

$diff_1+$diff_2= 1 年 6 个月 24 天

我需要的是计算和的diff_1总和diff_2

标签: phpdatetimedate-difference

解决方案


可能最简单的方法是创建一个新对象并克隆它,将两个(或更多) DateTimeIntervals (在您的情况下为$diff_1$diff_2)添加到新对象中。现在找到新对象与其克隆之间的差异是您最初拥有的两个 DateTimeIntervals 的总和。

// Define two intervals
$date1 = date_create("2013-03-15");
$date2 = date_create("2013-12-12");
$diff_1 = date_diff($date1,$date2);

$date3 = date_create("2015-02-15");
$date4 = date_create("2015-12-12");
$diff_2 = date_diff($date3,$date4);


// Create a datetime object and clone it
$dt = new DateTime();
$dt_diff = clone $result;

// Add the two intervals from before to the first one
$dt->add($diff_2);
$dt->add($diff_1);

// The result of the two intervals is now the difference between the datetimeobject and its clone
$result = $dt->diff($dt_diff);
var_dump($result);

转储结果包括

  ["y"]=>
    int(1)
  ["m"]=>
    int(6)
  ["d"]=>
    int(21)

..这是1年6个月21天。

现场演示

旁注
您不必将这么多不同的格式与您的format(). 您可以在一行中完成所有操作,

echo $result->format("%y years %m months %d days");

推荐阅读