Calculating trip time
Moderator: General Moderators
Calculating trip time
I am trying to take a number of calculated hours, say 2.4 hours, into standard time, i.e. 02:24. I'll take the seconds if I have to, but I can't seem to find a function that just takes a number as an argument like this and converts it to "time". Figured this is worth a shot before I try to write my own function.
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
you could try something like this:
UNTESTED:
UNTESTED:
Code: Select all
function fractionOfHours($time)
{
$thtime = explode(".",$time);
$fraction = number_format((60*$thtime[1])/10);
return $thtime[0].":".$fraction;
}
echo fractionOfHours(2.4);OK. Here is what I came up with. Anybody care to comment? Perhaps a simpler way to do this mathematically? This seems to work, but I don't often come up with very elegant solutions.
Code: Select all
function time_elapsed($dist, $speed){
global $hours;
global $minutes;
global $seconds;
$hours = intval($dist/$speed);
$minutes = intval(bcmod($dist,$speed)/$speed*60);
$seconds = (bcmod($dist,$speed)/$speed * 60 - $minutes) * 60;
if ($hours< 10){
$hours = '0'.$hours;
} else $hours = $hours;
if ($minutes< 10){
$minutes = '0'.$minutes;
} else $minutes = $minutes;
if ($seconds< 10){
$seconds = '0'.$seconds;
} else $seconds = $seconds;
}- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
Code: Select all
$time = 2.4; // in hours
$hours = bcdiv($time, 1, 0);
$remainder = bcsub($time, $hours, 4);
$remainder = bcmul($remainder, 60, 4);
$minutes = bcdiv($remainder, 1, 0);
$remainder = bcsub($remainder, $minutes, 4);
$remainder = bcmul($remainder, 60, 4);
$seconds = bcdiv($remainder, 1, 0);
$remainder = bcsub($remainder, $seconds, 4);
list(,$remainder) = explode('.', $remainder);
echo sprintf('%01s:%02s:%02s.%04s', $hours, $minutes, $seconds, $remainder);Thanks. I was passing the variables out to an echo stmt, but it makes more sense to do this inside the function now that you mention it. That gets rid of the global variables too. Now I am going to see if I can work through the logic of what Feyd did.Everah wrote:Kill the elses on your rewriting of hours, minutes and seconds, they are unnecessary. Also, your function doesn't return a value. How are you going to use it?
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA