Date difference interms of year/month/week/day/hour/minute/seconds

Some times we need to calculate date difference between 2 dates  in the format such as how many years or months or weeks or days or hours or minutes or seconds left from a particular date. Here is nice and simple solutions for this type of problem.


function compare_dates($date1, $date2) {
     $blocks = array(
         array('name' => 'year', 'amount' => 60 * 60 * 24 * 365),
         array('name' => 'month', 'amount' => 60 * 60 * 24 * 31),
         array('name' => 'week', 'amount' => 60 * 60 * 24 * 7),
         array('name' => 'day', 'amount' => 60 * 60 * 24),
         array('name' => 'hour', 'amount' => 60 * 60),
         array('name' => 'minute', 'amount' => 60),
         array('name' => 'second', 'amount' => 1)
     );

$diff = abs($date1 - $date2);

$levels = 2;
     $current_level = 1;
     $result = array();
     foreach ($blocks as $block) {
         if ($current_level > $levels) {
             break;
         }
         if ($diff / $block['amount'] >= 1) {
             $amount = floor($diff / $block['amount']);
             if ($amount > 1) {
                 $plural = 's';
             } else {
                 $plural = '';
             }
             $result[] = $amount . ' ' . $block['name'] . $plural;
             $diff -= $amount * $block['amount'];
             $current_level++;
         }
     }
     return implode(' ', $result);
 }

[NB: $date1 & $date2 must be in time stamp]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s