Just a quick and dirty little function to calculate the difference in time between two times.
Returns the number of years, weeks, days, hours, minutes and seconds between the two.
function getTimeDifference($time1, $time2) {
$dif = max($time1, $time2) - min($time1, $time2);
return array(
"years" => floor($dif/31536000),
"weeks" => floor(($dif%31536000)/604800),
"days" => floor((($dif%31536000)%604800)/86400),
"hours" => floor(($dif%86400)/3600),
"minutes"=> floor(($dif%3600)/60),
"seconds"=> $dif%60,
"earlier" => min($time1, $time2),
"later" => max($time1, $time2)
);
}
Here’s a little function to format the output:
function formatTimeDifference($dif) {
$ret = "";
$order = array("Years", "Weeks", "Days", "Hours", "Minutes", "Seconds");
foreach($order as $part) {
$v = $dif[strtolower($part)];
if ($v != 0) {
$ret .= strlen($ret) > 0 ? " " : "";
$ret .= $v." ";
$ret .= $v==1 ? substr($part, 0, -1) : $part;
}
}
return $ret;
}
And here’s how you might put it into action:
<?
echo "<pre>";
// First - the times
$time1 = strtotime("00:00 400 days ago");
$time2 = strtotime("today");
// Usage (doesn't matter which time is the earlier and which is the later)
$diff = getTimeDifference($time1 ,$time2);
// Output
echo "Difference between
· ".date('l dS \of F Y h:i:s A', $diff['earlier'])." and
· ".date('l dS \of F Y h:i:s A', $diff['later'])."
is:
";
print_r($diff);
echo "
".formatTimeDifference($diff);
echo "</pre>";
?>
Hope someone can find some use from it
Edit: bug fixed