Php 获取日期时间格式之间的持续时间

Php 获取日期时间格式之间的持续时间,php,Php,如何在php中以小时-分钟-秒格式获取开始日期和结束日期之间的持续时间 $start_date=2012-03-23 11:58:14 and $end_date=2012-03-24 11:54:29 此功能将帮助您 function datediff($interval, $datefrom, $dateto, $using_timestamps = false) { /* $interval can be: yyyy - Number of full years q -

如何在php中以小时-分钟-秒格式获取开始日期和结束日期之间的持续时间

$start_date=2012-03-23 11:58:14  and $end_date=2012-03-24 11:54:29

此功能将帮助您

function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
 /*
  $interval can be:
  yyyy - Number of full years
  q - Number of full quarters
  m - Number of full months
  y - Difference between day numbers
   (eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
  d - Number of full days
  w - Number of full weekdays
  ww - Number of full weeks
  h - Number of full hours
  n - Number of full minutes
  s - Number of full seconds (default)
 */

  • 将这些字符串设置为最新格式
  • 将这些日期转换为毫秒
  • 开始日期
  • 根据结果计算h:mm:ss

  • 使用
    DateTime
    类:

    $start_date = new DateTime('2012-03-23 11:58:14');
    $end_date = new DateTime('2012-03-24 11:54:29');
    
    $dd = date_diff($end_date, $start_date);
    
    要获得小时数,请使用
    $dd->h
    ,分钟-
    $dd->i
    ,秒-
    $dd->s

    echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
    
    我会的

    $start_time = strtotime($start_date);
    $end_time = strtotime($end_date);
    $difference = $end_time - $start_time;
    echo date('H:i:s', $difference);
    
    编辑

    我错误地假设时差小于一天,因此如果时差大于一天,您将只看到小时:分钟:秒,这可能不是您想要的(如果是,请忽略此)

    所以我现在想

    $seconds = $difference % 60;            //seconds
    $difference = floor($difference / 60);
    $min = $difference % 60;              // min
    $difference = floor($difference / 60);
    $hours = $difference;  //hours
    echo "$hours : $min : $seconds";
    
    抱歉进行了更正

    请在此处查看它的工作情况:


    在这里,你没有考虑时间区为什么要考虑时区,他正在计算差异,这将总是返回“23:56:15”,即使$STATIONDATE改为“2012-03-22:11:58:14”(一天前),我们需要像年、月、日、小时和秒的格式,我可以计算H:mm:SS?
    $start_date="2012-03-22 11:58:14";
    $end_date="2012-03-24 11:54:29";
    
    $start_time = strtotime($start_date);
    $end_time = strtotime($end_date);
    $difference = $end_time - $start_time;
    
    echo sprintf("%02d%s%02d%s%02d", floor($difference/3600), ':', ($difference/60)%60, ':', $difference%60); // outputs 47:56:15