如何找到2次之间的差异?

时间:2018-09-07 05:20:11

标签: php codeigniter time controller

插入时间的控制器功能:

$input = $this->input->post('shiftStartTime');
$input = str_replace(" : ", ":", $input);
$shiftstarttime = date('H:i:s', strtotime($input));

$input2 = $this->input->post('shiftEndTime');
$input2 = str_replace(" : ", ":", $input2);
$shiftEndTime = date('H:i:s', strtotime($input2));

我想计算2倍之间的时差

这是我的代码,但是显示的时差错误。如何解决?

$input3 = $this->input->post('shiftEndTime')-$this->input->post('shiftStartTime');
$input3 = str_replace(" : ", ":", $input3);
$duration = date('H:i:s', strtotime($input3));

3 个答案:

答案 0 :(得分:1)

尝试使用此diff函数

<?php
$input = $this->input->post('shiftStartTime');
$input = str_replace(" : ", ":", $input);
$shiftstarttime = date('H:i:s', strtotime($input));

$input2 = $this->input->post('shiftEndTime');
$input2 = str_replace(" : ", ":", $input2);
$shiftEndTime = date('H:i:s', strtotime($input2));
echo date_create($shiftEndTime)->diff(date_create($shiftstarttime))->format('%H:%i:%s');
?>

答案 1 :(得分:0)

有两种方法可以计算两次之间的差异

   // example 1
$time1 = "08:00:00";
$time2 = "13:40:00";

echo "Time difference: ".get_time_difference($time1, $time2)." hours<br/>";

// example 2
$time1 = "22:00:00";
$time2 = "04:00:00";

echo "Time difference: ".get_time_difference($time1, $time2)." hours<br/>";

function get_time_difference($time1, $time2)
{
    $time1 = strtotime("1/1/1980 $time1");
    $time2 = strtotime("1/1/1980 $time2");

if ($time2 < $time1)
{
    $time2 = $time2 + 86400;
}

return ($time2 - $time1) / 3600;

}

source code reference

Author profile

答案 2 :(得分:0)

use below code to find the time difference between two times.

$input = $this->input->post('shiftStartTime');
$input = str_replace(" : ", ":", $input); 
$input2 = $this->input->post('shiftEndTime');
$input2 = str_replace(" : ", ":", $input2);   
$date_a = new DateTime($input);
$date_b = new DateTime($input2);
$interval = date_diff($date_a,$date_b);
$diff = $interval->format('%h:%i:%s');