0

Controller Function to insert time:

$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));

I want to take the time difference between 2 times

Here is my code,but it shows wrong difference time.How to solve it?

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

3 Answers3

1

try with this diff function

<?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');
?>
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
0

There is multiple way to calculate difference between two times

   // 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

Bilal Ahmed
  • 4,005
  • 3
  • 22
  • 42
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');
Sachin
  • 789
  • 5
  • 18