...

View Full Version : Issue in getting the time difference between two variables



newphpcoder
01-30-2012, 04:29 AM
I have two textboxes that inputted time, and I want to get the difference between two time.

for example:

$IN = 13:35;
$OUT = 17:35;

$OTHours = ($OUT - $IN);

$OTHours = 4.00;


and it is correct, but I have a scenario like this:

$IN = 21:35;
$OUT = 05:35;

$OTHours = -16.00;

it should be 8.00.

Any help is highly appreciated.

Thank you..

jmj001
01-30-2012, 05:18 AM
convert the time to timestamp which gives you a seconds value, then subtract the latest from the earliest and you have the time difference in seconds...

multiply the answer by 60 for minutes
60 * 60 for hours etc...

you will need full date and time

newphpcoder
01-30-2012, 05:50 AM
What if i add date in time and i used strtotime is it much ok?how?


Thank you

jmj001
01-30-2012, 06:20 AM
yep..


$thisTime1 = date("U",strtotime($somedate_from_myform));
$thisTime2 = date("U",strtotime($somedate_from_myform2));
$timeDiff = $thisTime2 - $thisTime1;

KuriosJon
01-30-2012, 11:33 AM
yep..


$thisTime1 = date("U",strtotime($somedate_from_myform));
$thisTime2 = date("U",strtotime($somedate_from_myform2));
$timeDiff = $thisTime2 - $thisTime1;

date("U") is redundant when used like that. All you need is:


$in_timestamp = strtotime($IN);
$out_timestamp = strtotime($OUT);
$difference = $out_timestamp - $in_timestamp;

That gives you $difference in seconds, so you can convert that to hours and minutes if you want.

Fou-Lu
01-30-2012, 01:56 PM
An alternative on 5.3+ is to use datetime and dateinterval. Dateinterval is always the difference, and sign is not included unless explicitly specified:


$dt1 = new DateTime('13:35');
$dt2 = new DateTime('17:17');

$dtdiff = $dt1->diff($dt2);
print $dtdiff->format('%h hours, %i minutes');

That will print '3 hours, 42 minutes'.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum