Finding the difference between dates
August 7th, 2007
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!
Add to del.icio.us
Digg this
Technorati
Related Posts:
- Dates & MySQL
- Count occurence of character (i.e. line breaks) in a MySQL field
- The Ubiquitous Bloke in the Pub
- Regular Expressions in PHP
- AJAX is evil
Entry Filed under: PHP
2 Comments Add your own
1. Mutiny Design | August 17th, 2007 at 11:04 pm
Thanks for this. Saved me an hour or two
2. Justin | December 4th, 2007 at 5:27 pm
Thanks for this!
I modified your function to allow for an additional 'format' argument. 'format' allows you to customize the returned string.
function dateDiff($from,$to,$format='%%D%% d, %%H%% h, %%M%% m, %%S%% s'){
$diff = $to - $from;
$info = array('d'=>0,'h'=>0,'m'=>0,'s'=>0);
if($diff>86400) {
$info['d'] = ($diff - ($diff%86400))/86400;
$diff = $diff%86400;
}
if($diff>3600) {
$info['h'] = ($diff - ($diff%3600))/3600;
$diff = $diff%3600;
}
if($diff>60) {
$info['m'] = ($diff - ($diff%60))/60;
$diff = $diff%60;
}
if($diff>0) {
$info['s'] = $diff;
}
return str_replace(array('%%D%%','%%H%%','%%M%%','%%S%%'),array($info['d'],$info['h'],$info['m'],$info['s']),$format);
}
You can see it in action in the 'about us' section here.
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed