【问题标题】:Adding time PHP添加时间 PHP
【发布时间】:2013-02-19 19:06:09
【问题描述】:

我正在尝试使用这些变量中捕获的开始时间和结束时间。我想将这些值加在一起以获得花费在各种任务上的总时间。所以我得到了这些价值观,并试图做这样的事情:

//start times
$time_1 = $_POST['start_of_service_1'];
$time_2 = $_POST['start_of_service_2'];
$time_3 = $_POST['start_of_service_3'];

//end times
$etime_1 = $_POST['end_of_service_1'];
$etime_2= $_POST['end_of_service_2'];
$etime_3 = $_POST['end_of_service_3'];

//total hours
$tot_hours_1 = date('H:i',strtotime($etime_1)-strtotime($time_1);
$tot_hours_2 = date('H:i',strtotime($etime_2)-strtotime($time_2));
$tot_hours_3 = date('H:i',strtotime($etime_3)-strtotime($time_3));

$totaltime = $tot_hours_1 + $tot_hours_2 + $tot_hours_3

因此,如果时间跨度为每 5 分钟,则总计 00:05 + 00:05 + 00:05 = 00:15 分钟。

这些时间函数看起来很棘手,我遇到了可怕的麻烦,并且花了很多时间来克服这个障碍。

谁能给我建议如何做到这一点?

【问题讨论】:

  • 我推荐使用 DateTime,类似的问题:stackoverflow.com/a/2767124/1611108
  • 您不能使用 + 将日期格式的时间添加到另一个日期格式的时间。我认为这不会返回您的期望。为什么不直接使用$tot_hours_1 = strtotime($etime_1) - strtotime($time_1); 获取所有差异,然后简单地将所有 $tot_hours_1/2/3 加在一起。 THEN 使用 date 函数格式化最终结果。

标签: php


【解决方案1】:

只需删除date('H:i', 和对应的)。这将为您留下可以相加的数字。使用date() 格式化应该是您最后 做的事情。

【讨论】:

  • 谢谢大家。我最终使用了上面的第二个解决方案。最后,我将总小时数转换为十进制。
【解决方案2】:

您正尝试在$totaltime = $tot_hours_1 + $tot_hours_2 + $tot_hours_3 这一行中添加date formats。无法使用+ 添加Time 格式。尝试仅添加纯数字,然后使用date() 对其进行格式化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    相关资源
    最近更新 更多