Archive for August 7th, 2007

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:
  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!

2 comments August 7th, 2007


Calendar

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

Posts by Month

Posts by Category