我希望消耗完美的时间或从开始时间到结束时间的总时间:
我的代码:
$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;
}
在上面的代码中$start_time
= 11:00:00 PM
和$end_date =11:30:00
,它为我提供了0.5
而不是30minutes
的输出。有没有合适的方法来做到这一点?
所以如果:
$start_time = '01:00:00 PM';
$end_time = '01:25:00 PM';
$total = '25:00'; // 25 minutes
或:
$start_time = '11:00:00 PM';
$end_time = '11:00:25 PM';
$total = '00:00:25'; // 25seconds
问候!
答案 0 :(得分:4)
尝试diff功能
<?php
echo date_create('03:00:00 PM')->diff(date_create('03:25:00 PM'))->format('%H:%i:%s');
?>
输出
00:25:00
答案 1 :(得分:1)
尝试使用diff:
echo date_create('01:00:00 PM')->diff(date_create('01:25:00 PM'))->format('%H:%i:%s');
答案 2 :(得分:0)
您可以使用strtotime()进行时间计算。这是一个例子:
$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.';
}
输出:
Time 1: 09:00:59
Time 2: 09:01:00
Diff: 00:00:01
答案 3 :(得分:0)
你必须使用if和else语句检查所有内容。 我觉得这个有帮助。
$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));