Click to See Complete Forum and Search --> : Time Difference script required


Typhoon101
04-16-2005, 03:26 AM
Hi. I have been trying to do this myself for a little while, but have not had any sort of success. I am not too familiar with date functions in PHP yet.

I have a database, that contains two date/time fields. The format for each date is YYYY-MM-DD h:m:s. e.g. 2005-04-16 09:17.

What i need to do is calculate the difference between these two values in hours, rounded up to the nearest whole hour.

So, if $startDate = 2005-04-16 09:17 and $endDate = 2005-04-17 09:27, the result would be 25 hours, even though the actual difference is 24 hours and 10 minutes.

Can anyone help?

scragar
04-16-2005, 07:14 AM
$startDate = "2005-04-16 09:17:05";
$endDate = "2005-04-17 09:27:03";
$startArray = explode(" ", $startDate);
$startDay = explode("-", $startArray[0]);
$startTime = explode("-", $startArray[1]);
$endArray = explode(" ", $endDate);
$endDay = explode("-", $endArray[0]);
$endTime = explode("-", $endArray[1]);
$startExact = mktime($startTime[0], $startTime[1], $startTime[2], $startDay[1], $startDay[0], $startDay[2]);
$endExact = mktime($endTime[0], $endTime[1], $endTime[2], $endDay[1], $endDay[0], $endDay[2]);
$diff = $startExact - $endExact;
$diff = ceil($diff / 60);//sec's to mins
$diff = ceil($diff / 60);//mins to hours.
echo $diff;

Typhoon101
04-16-2005, 09:32 AM
Thanks Scragar.

I have copied the text exactly as written, and i get a value of -8760 though. Have i forgotten something?

NogDog
04-16-2005, 11:36 AM
I'm thinking this might be a little simpler:

$query = <<<EOD
SELECT UNIX_TIMESTAMP(`end_date`) - UNIX_TIMESTAMP(`start_date`)
FROM `table_name` WHERE `key_field` = '$some_value'
EOD;

$result = mysql_query($query);
$row = mysql_fetch_array($result);
$intervalHours = ceil($row[0]/60/60);

Typhoon101
04-16-2005, 05:06 PM
That worked great. Thank you NogDog.