【问题标题】:How do I add, accumulate, sum time diff in PHP?如何在 PHP 中添加、累积、求和时间差异?
【发布时间】:2014-01-06 22:00:37
【问题描述】:

我正在尝试添加与 php 日期时间对象的差异,但我做错了。我得到了我期望的时差:

$total = 00:11:33 $accumulator = 00:05:47

但是如何添加 DateIntervals?还是我只是创建一个新的 dateTime 对象并添加到它?

$total = new DateInterval('P0000-00-00T00:00:00');
$accumulator = new DateInterval('P0000-00-00T00:00:00');
$a = new DateTime('2014-01-05 00:01:38');
$b = new DateTime('2014-01-05 00:13:11');
$c = new DateTime('2014-01-05 00:18:58');
$d = new DateTime('2014-01-05 00:24:45');

$total = $a->diff($b);
$accumulator =  $c->diff($d);

echo '$total = ' . $total->format("%H:%I:%S");
echo '$accumulator = ' . $accumulator->format("%H:%I:%S");

$total += $accumulator;

echo 'Grand Total = ' . $total->format("%H:%I:%S");

【问题讨论】:

  • 你用错了->format()。它不使用% 作为其格式字符,I 将对应于 DST-in-effect 标志,而不是分钟。你想要->format('H:i:s')S 也是 2nd/3rd/4th 后缀。..s(小写)是秒。
  • 你为什么要用new DateInterval初始化$totalaccumulator,而你只是要用diff的结果替换它们?
  • 您不能将DateInterval+ 添加。看起来根本不可能添加DateInterval。您只能将它们添加到DateTime。我认为这是因为月份和年份等间隔取决于您从哪里开始,因为月份长度和闰年不同。
  • 感谢您的帮助。 Barmar,我在这里的 PHP 文档中找到了 DateInterval 的格式:link。我想我将使用时间设置为 00:00 的新日期对象并添加到它。我只需要总时间,它会少于 23 小时 59 分钟,所以我想这会奏效。

标签: php datediff


【解决方案1】:

也许您想使用 Carbon 扩展。 https://github.com/briannesbitt/Carbon

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2022-07-24
    • 2022-10-02
    • 2022-01-17
    • 2019-10-07
    • 2016-03-16
    • 2021-04-07
    相关资源
    最近更新 更多