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:
  1. <?php
  2. function dateDiff($from,$to) {
  3.   $diff = $to - $from;
  4.   $info = array();
  5.   if($diff>86400) {
  6.     //one or more days
  7.     $info['d'] = ($diff - ($diff%86400))/86400;
  8.     $diff = $diff%86400;
  9.   }
  10.   if($diff>3600) {
  11.     //one or more hours
  12.     $info['h'] = ($diff - ($diff%3600))/3600;
  13.     $diff = $diff%3600;
  14.   }
  15.   if($diff>60) {
  16.     //one or more minutes
  17.     $info['m'] = ($diff - ($diff%60))/60;
  18.     $diff = $diff%60;
  19.   }
  20.   if($diff>0) {
  21.     $info['s'] = $diff;
  22.   }
  23.   $f = '';
  24.   foreach($info as $k=>$v) {
  25.     if($v>0) $f .= "$v $k, ";
  26.   }
  27.   return substr($f,0,-2);
  28. }
  29. ?>

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:
  1. <?php
  2. echo dateDiff(1186233948,1186480322); //2 d, 20 h, 26 m, 14 s
  3. echo dateDiff(1186233948,time()); //3 d, 1 h, 22 m, 7 s
  4. ?>

Enjoy!


 Add to del.icio.us    Digg this    Technorati

Related Posts:

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

Required

Required, hidden

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


Calendar

August 2007
M T W T F S S
« Apr   Sep »
 12345
6789101112
13141516171819
20212223242526
2728293031  

Most Recent Posts