php添加和减去时间

Im attempting to code a little script that will work out hours.

I would like a travel time, start time and a finish time. The problem I'm having is getting the total time.

$travel = $_POST['travel'];  // -- 1.00 (1 hour)
$start = $_POST['start'];    // -- 7.30 
$finish = $_POST['finish'];  // -- 16.00 

so the total time would be ( 16.00 - 7.30 ) + 1.00 = 9.5 hours

But this doesn't work because 16.00 - 7.30 = 8.7, then plus the 1 = 9.7.

I understand why its wrong, but not how to fix it. I cant change the time values to .50 for the half hour because the value is coming from a jquery plugin. Any help would be much appreciated.

// update

$a = new DateTime($_POST['start']);
$b = new DateTime($_POST['finish']);
$interval = $a->diff($b);

echo $interval->format("%H");

This works great, the only thing is how do I display hours and minutes e.g '9.00'

update

Since you changed your question... Looking at the syntax for DateTime::format(),

echo $interval->format("H.i");

should give you the formatting you want.

old answer

The easiest way to deal with time is by representing each time as a number of seconds. (If it's a date, use the number of seconds since the epoch.) You can write some helper functions to convert your times to/from the formats that you want.

For example,

16.00 -> 57600  
7.30 -> 27000  
1.00 -> 3600

(57600 - 27000) + 3600 = 34200  
34200 -> 9.30

here are the helper functions I came up with:

function timeToSeconds ($time) {
    $hours = floor($time);
    $minutes = ($time - $hours) * 100;
    $seconds = ($hours * 3600) +  ($minutes * 60);
    return $seconds;
}

function secondsToTime ($seconds) {
    $hours = floor($seconds / 3600);
    $minutes = ($seconds - ($hours * 3600)) / 60;
    $time = "" . $hours . "." . $minutes;
    return $time;
}

You could try something like this

<?php
$travel =1.00;  // -- 1.00 (1 hour)
$start = 7.30;    // -- 7.30 
$finish = 16.00;  // -- 16.00 
//do the sum
$sum = $finish-$start+$travel;
//get minutes
$exp = explode(".",$sum);
$minutes = $exp[1];
//if $minutes has only one digit, add a 0
if(strlen($minutes)<2){$minutes .= 0;}
//if $minutes are more than 59, convert them in hours
if($minutes>59){
//it would be $sum-0.6+1
$new_sum = $sum+0.4;
}
else{
$new_sum = $sum;
}
echo $minutes.'<br>'.$sum.'<br>'.$new_sum;
?>

This example will out-put 70 9.7 10.1