Finding the difference between dates
I needed a quick and easy to produce a human readable difference between two dates, and came up with the follwing:
PHP:
-
<?php
-
function dateDiff($from,$to) {
-
$diff = $to - $from;
-
if($diff>86400) {
-
//one or more days
-
$info['d'] = ($diff - ($diff%86400))/86400;
-
$diff = $diff%86400;
-
}
-
if($diff>3600) {
-
//one or more hours
-
$info['h'] = ($diff - ($diff%3600))/3600;
-
$diff = $diff%3600;
-
}
-
if($diff>60) {
-
//one or more minutes
-
$info['m'] = ($diff - ($diff%60))/60;
-
$diff = $diff%60;
-
}
-
if($diff>0) {
-
$info['s'] = $diff;
-
}
-
$f = '';
-
foreach($info as $k=>$v) {
-
if($v>0) $f .= "$v $k, ";
-
}
-
}
-
?>
Usage:
Just ensure that you pass it two timestamps, the first one being the date FROM when you want to calculate, the second one being where you want it calculated TO. Tip: You can get the current timestamp by using time().
PHP:
Enjoy!
2 comments August 7th, 2007