【问题标题】:how to count the difference between the two time in php and show it如何在php中计算两次时间之间的差异并显示出来
【发布时间】:2020-05-17 19:21:55
【问题描述】:

我需要在 PHP 中显示两次之间的差异我使用 strtotime() 函数将我的时间转换为整数,但我的问题是结果与我的预期不符

<?php
$hour1 = '12:00:00';
$hour2 = '9:00:00';
$avg = strtotime($hour1) - strtotime($hour2);
$result = date('h:i:s', $avg); // result = 06:30:00 what I expected is 3:00:00

但是相差3:00:00这个怎么算?

【问题讨论】:

  • strtotime()date 似乎不是这项工作的正确工具。

标签: php php-7 php-5.6 php-7.2


【解决方案1】:

您可以创建DateTime 实例并使用diff 函数来获取2 次之间的差异。然后,您可以将它们格式化为小时、分钟和秒。

<?php

$hour1 = '12:00:00';
$hour2 = '09:00:00';

$o1 = new DateTime($hour1);
$o2 = new DateTime($hour2);

$diff = $o1->diff($o2,true); // to make the difference to be always positive.

echo $diff->format('%H:%I:%S');

演示: https://3v4l.org/X41pv

【讨论】:

    【解决方案2】:

    你可以这样做:

    $hour1 = '12:00:00';
    $hour2 =  date('h', strtotime('9:00:00')); 
    $avg= date('h:i:s', strtotime($hour1. ' - '.$hour2.' hours') );
    echo $avg; //3:00:00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 2018-04-03
      • 2012-04-01
      • 1970-01-01
      相关资源
      最近更新 更多