php adding and subtracting time -
im attempting code little script work out hours.
i travel time, start time , finish time. problem i'm having getting total time.
$travel = $_post['travel']; // -- 1.00 (1 hour) $start = $_post['start']; // -- 7.30 $finish = $_post['finish']; // -- 16.00
so total time ( 16.00 - 7.30 ) + 1.00 = 9.5 hours
but doesn't work because 16.00 - 7.30 = 8.7, plus 1 = 9.7.
i understand why wrong, not how fix it. cant change time values .50 half hour because value coming jquery plugin. appreciated.
// update
$a = new datetime($_post['start']); $b = new datetime($_post['finish']); $interval = $a->diff($b); echo $interval->format("%h");
this works great, thing how display hours , minutes e.g '9.00'
update
since changed question... looking @ syntax datetime::format(),
echo $interval->format("h.i");
should give formatting want.
old answer
the easiest way deal time representing each time number of seconds. (if it's date, use number of seconds since epoch.) can write helper functions convert times to/from formats want.
for example,
16.00 -> 57600 7.30 -> 27000 1.00 -> 3600 (57600 - 27000) + 3600 = 34200 34200 -> 9.30
here helper functions came 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; }
Comments
Post a Comment