【问题标题】:How calculate the sum of two DateInterval object如何计算两个 DateInterval 对象的总和
【发布时间】:2019-02-11 06:36:00
【问题描述】:

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

$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_1diff_2 的总和?

【问题讨论】:

标签: php datetime date-difference


【解决方案1】:

可能最简单的方法是创建一个新对象并克隆它,将两个(或更多)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 天。

Live demo

旁注
您不必使用format() 连接这么多不同的格式。您可以在一行中完成所有操作,

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

【讨论】:

    【解决方案2】:

    您可以将两个 DateInterval 对象添加到新的 DateTime 对象中,然后再次计算差异。

    <?php
    
    $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
    
    $today = new DateTime();
    $today->add($diff_1);
    $today->add($diff_2);
    $diff_total = $today->diff(new DateTime());
    
    echo $diff_total->format("%y years").' '.$diff_total->format("%m months"). ' ' . $diff_total->format("%d days");
    

    【讨论】:

    • 如果不克隆$today,您最终可能会略有不同。在一些不明显的情况下可能会改变结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 2021-02-24
    • 2017-01-17
    相关资源
    最近更新 更多