How to calculate the time consumed from start time

2019-08-20 18:15发布

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!

4条回答
成全新的幸福
2楼-- · 2019-08-20 18:39

Try using diff:

echo date_create('01:00:00 PM')->diff(date_create('01:25:00 PM'))->format('%H:%i:%s');
查看更多
做自己的国王
3楼-- · 2019-08-20 18:43

You can use strtotime() for time calculation. Here is an example:

$start_time = strtotime('09:00:59');
$end_time = strtotime('09:01:00');
$diff = $start_time - $end_time;
echo 'Time 1: '.date('H:i:s', $start_time).'<br>';
echo 'Time 2: '.date('H:i:s', $end_time).'<br>';

if($diff){
    echo 'Diff: '.date('H:i:s', $diff);
}else{
    echo 'No Diff.';
}

Output:

Time 1: 09:00:59
Time 2: 09:01:00
Diff: 00:00:01
查看更多
forever°为你锁心
4楼-- · 2019-08-20 18:59

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
查看更多
相关推荐>>
5楼-- · 2019-08-20 19:03

You have to check everything using if and else statement. I think this one help.

 $start_time =  "11:00:00";
 $end_time =  "12:30:00";


  $t1  = strtotime($start_time);
  $t2 = strtotime($end_time);
  $difference = $t2 - $t1;


  if($difference / 3600 > 0){
     $hour = $difference / 3600;
     $hour = (int)$hour;

     $difference = $difference - ($hour * 3600);

  }else{
     $hour = "00";
  }

  if($difference / 60 > 0){
       $min = $difference / 60;

       $difference = $difference - ($min * 60);

  }else{
       $min = "00";
  }
  function checkString($str){
        if(strlen($str)==1){
        return "0".$str;
    }
    return $str;
  }
  print_r(checkString($hour).":".checkString($min).":".checkString($difference));
查看更多
登录 后发表回答