php - 如何计算两个 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
?
解决方案
可能最简单的方法是创建一个新对象并克隆它,将两个(或更多) 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");
推荐阅读
- docker - Docker:您的系统中缺少请求的 PHP 扩展 bcmath
- java - Java注解处理器:javax.validation.constraints.Past注解改变了字段类型
- c++ - 在 .NET 中调用 c++ 代码时应用程序崩溃
- c++ - 仅使用一次 CMake 时,如何使用 2 个不同的 main.cpp 文件制作 2 个不同的可执行文件?
- testng - TestNG 初始化对象初始化失败
- vba - 是否可以将邮件合并数据源的值放入数组变量中?
- angular - How to get array in child component Angular?
- javascript - 我在调度一个动作之前使用 setState 设置一个属性,但是在调度时的 redux 动作中没有设置该属性
- excel - Excel比较表以查找二维数组中的存在
- reactjs - 我们可以将 kafka 与 react native 集成吗