Skip to content
Advertisement

How to calculate the time consumed from start time to end time in php

I want to get the perfect time consumed or the total time from start time to end time:
My code:

   $start_time =  $this->input->post('start_time');
   $end_time =  $this->input->post('end_time');


   $t1  = strtotime($start_time);
   $t2 = strtotime($end_time);
   $differenceInSeconds = $t2 - $t1;
   $differenceInHours = $differenceInSeconds / 3600;

   if($differenceInHours<0) {
     $differenceInHours += 24; 
    }

In the code above if $start_time = 11:00:00 PM and $end_date =11:30:00 it gives me the output of 0.5 instead of 30minutes. Is there any appropriate way to do it like that?
So if the:

  $start_time  = '01:00:00 PM';
  $end_time = '01:25:00 PM';

  $total = '25:00'; // 25 minutes

or:

  $start_time  = '11:00:00 PM';
  $end_time = '11:00:25 PM';

  $total = '00:00:25'; // 25seconds

Regards!

Advertisement

Answer

Try diff function

<?php
echo date_create('03:00:00 PM')->diff(date_create('03:25:00 PM'))->format('%H:%i:%s');
?>

Output


00:25:00
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement