如何获取php中两个时间值之间的时差

时间:2015-01-22 05:24:24

标签: php

我的问题是,如何在不获得负输出的情况下计算时间值之间的差异。我在计算时差方面没有问题,但问题出现的时候是这样的:

timein:23:00 注意:m_time是timein

超时:08:00 注意:mx_time超时

这是我的代码,可以得到时差:

$start_time = explode(":",$m_time);   //where m_time = 10:32
$start_time_hr = $start_time[0];
$start_time_min = $start_time[1];
$start_tot_min = intval($start_time_hr*60) + $start_time_min;

$end_time = explode(":",$mx_time);   //where mx_time = 11:45

$end_time_hr = $end_time[0];
$end_time_min = $end_time[1];

$end_tot_min = intval($end_time_hr*60) + $end_time_min; //converting hour to min + min

$total_min_diff = intval($end_tot_min - $start_tot_min);

hr_diff = intval($total_min_diff/60);    
min_diff = intval($total_min_diff%60);


<?php echo "The total Difference Is : ".$hr_diff." Hours & ".$min_diff." Minutes.";?>

谢谢!

2 个答案:

答案 0 :(得分:3)

建议在发现超时时间小于时间时间时添加日(24小时)。

$start_time = explode(":",$m_time);
$start_time_hr = $start_time[0];
$start_time_min = $start_time[1];
$start_tot_min = intval($start_time_hr*60) + $start_time_min;

$end_time = explode(":",$mx_time);
$end_time_hr = $end_time[0];

// Add a day if end time smaller than start time
if($end_time_hr<$start_time_hr){
    $end_time_hr += 24;
}

$end_time_min = $end_time[1];
$end_tot_min = intval($end_time_hr*60) + $end_time_min; //converting hour to min + min

$total_min_diff = intval($end_tot_min - $start_tot_min);

$hr_diff = intval($total_min_diff/60);    
$min_diff = intval($total_min_diff%60);

希望这有帮助:D

答案 1 :(得分:1)

将时间转换为秒,然后取差值,然后将差异(以秒为单位)转换为小时,分钟。