我正在尝试计算通过时间选择器输入的两次之间的时差(以小时为单位)。我有JavaScript代码,但宁可使用服务器端代码进行此计算,因为它非常重要。如果您希望我发布正在运行的JS代码,请在评论中告诉我。
计算时间之间的差异很容易,但我需要以特定格式输出。例如,'07:30'和'14:00'的输入将返回6.5而不是6.3。这样做的原因是为了让我更容易在计算中使用这个时间差。
PHP代码我试过:
尝试#1:
<?php
$start_time = new DateTime('07:30');
$end_time = new DateTime('14:00');
$time_diff = date_diff($start_time,$end_time);
echo $time_diff->format('%h.%i');
?>
按预期返回6.3。
尝试#2:
<?php
$start_time = "07:30";
$end_time = "14:00";
$start_time = str_replace(":", "", $start_time);
$end_time = str_replace(":", "", $end_time);
$res = $end_time - $start_time;
$result = $res / 100;
echo $result;
?>
返回6.7。
用于测试输出的工具:http://codepad.viper-7.com/
答案 0 :(得分:2)
只需提取分钟:
<?php
$start_time = new DateTime('07:30');
$end_time = new DateTime('14:00');
$time_diff = date_diff($start_time,$end_time);
$hours = (int)$time_diff->format('%h');
$hour_part = ((int)$time_diff->format('%i')) / 60;
echo $hours + $hour_part;
?>
确保在进行任何计算之前将类型更改为(int)
如果将分钟数除以60,您将得到它们代表的一小时。
答案 1 :(得分:1)
<?php
$start_time = new DateTime('07:30');
$end_time = new DateTime('14:00');
$time_diff = date_diff($start_time,$end_time);
echo $time_diff->format('%h') + $time_diff->format('%i')/60;
?>
按预期返回6.5。
答案 2 :(得分:0)
你可以试试这个:
<?php
$start_time = strtotime("07:30");
$end_time = strtotime("14:00");
$diff = $end_time - $start_time;
echo $diff;
答案 3 :(得分:0)
您可以使用此功能获取两次之间的时差:
function timeBetween($start_date,$end_date)
{
$diff = $end_date-$start_date;
$seconds = 0;
$hours = 0;
$minutes = 0;
if($diff % 86400 <= 0){$days = $diff / 86400;} // 86,400 seconds in a day
if($diff % 86400 > 0)
{
$rest = ($diff % 86400);
$days = ($diff - $rest) / 86400;
if($rest % 3600 > 0)
{
$rest1 = ($rest % 3600);
$hours = ($rest - $rest1) / 3600;
if($rest1 % 60 > 0)
{
$rest2 = ($rest1 % 60);
$minutes = ($rest1 - $rest2) / 60;
$seconds = $rest2;
}
else{$minutes = $rest1 / 60;}
}
else{$hours = $rest / 3600;}
}
if($days > 0){$days = $days.' days, ';}
else{$days = false;}
if($hours > 0){$hours = $hours.' hours, ';}
else{$hours = false;}
if($minutes > 0){$minutes = $minutes.' minutes, ';}
else{$minutes = false;}
$seconds = $seconds.' seconds';
return $days.''.$hours.''.$minutes.''.$seconds;
}
答案 4 :(得分:0)
1小时= 60分钟。 Demo.
$start_time = "07:30";
$end_time = "14:00";
list($h1, $m1) = explode(':', $start_time);
list($h2, $m2) = explode(':', $end_time);
// 1 hr = 60 min
$res = ($h2*60 - $m2) - ($h1*60 + $m1);
$result = floor($res/60) .'.'. $res % 60;
echo $result;
答案 5 :(得分:0)
试试这个
function time_difference($ time1,$ time2){
$time1 = strtotime("1980-01-01 $time1");
$time2 = strtotime("1980-01-01 $time2");
if ($time2 < $time1) {
$time2 += 86400;
}
返回日期(&#34; H:i:s&#34;,strtotime(&#34; 1980-01-01 00:00:00&#34;)+($ time2 - $ time1)); }
echo time_difference(&#34; 11:30:30&#34;,&#34; 22:40:59&#34;);