I am trying to make a function to calculate the time difference of two values, but my return in my code below gives me unexpected string, how come?
var mf_start_time = "10:30:30"; var mf_end_time = "11:10:10"; function time_interval(mf_start_time,mf_end_time) { $s = strtotime($start_time); $e = strtotime($end_time); if ($s < $e) { $a = $e - $s; } else { $e = strtotime('+1 day',$e); $a = $e - $s; } $h = floor($a/3600); $m = floor(($a%3600)/60); $s = $a%60; return trim(($h?$h.' hour ':'').($m?$m.' minute ':'').($s?$s.' second ':'')); }
Advertisement
Answer
You do appear to be getting the syntax of Javascript and PHP mixed up. There is no var
in PHP – that belongs in Javascript and variables in PHP begin with $
A few minor tweaks to your code:
$mf_start_time = "10:30:30"; $mf_end_time = "11:10:10"; function time_interval($mf_start_time,$mf_end_time) { $s = strtotime($mf_start_time); $e = strtotime($mf_end_time); if ($s < $e) { $a = $e - $s; } else { $e = strtotime('+1 day',$e); $a = $e - $s; } $h = floor($a/3600); $m = floor(($a%3600)/60); $s = $a%60; return trim(($h?$h.' hour ':'').($m?$m.' minute ':'').($s?$s.' second ':'')); } echo time_interval($mf_start_time,$mf_end_time);
Yields:
39 minute 40 second