Tag: date

2010-08-03

Expressing the Difference Between 2 Dates/Times

by Charles — Categories: PHP — Tags: , , Leave a comment

In an effort to consolidate some things I’ve posted on my site in a less organized manner, here is a reprint of a function I came up with a few years ago for expressing the difference between two UNIX timestamp values (such as returned from the time() and mktime() functions). The result is an array of years, months, weeks, days, hours, minutes, and seconds.


<?php
/**
* Get difference between timestamps broken down into years/months/weeks/etc.
* @return array
* @param int $t1 UNIX timestamp
* @param int $t2 UNIX timestamp
*/
function timeDiff($t1$t2)
{
   if($t1 $t2)
   {
      $time1 $t2;
      $time2 $t1;
   }
   else
   {
      $time1 $t1;
      $time2 $t2;
   }
   $diff = array(
      'years' => 0,
      'months' => 0,
      'weeks' => 0,
      'days' => 0,
      'hours' => 0,
      'minutes' => 0,
      'seconds' =>0
   );
   foreach(array('years','months','weeks','days','hours','minutes','seconds')
         as $unit)
   {
      while(TRUE)
      {
         $next strtotime("+1 $unit"$time1);
         if($next $time2)
         {
            $time1 $next;
            $diff[$unit]++;
         }
         else
         {
            break;
         }
      }
   }
   return($diff);
}

Here’s a sample usage:


<?php
$start strtotime('2007-01-15 07:35:55');
$end strtotime('2009-11-09 13:01:00');
$diff timeDiff($start$end);
$output "The difference is:";
foreach($diff as $unit => $value)
{
   echo " $value $unit,";
}
$output trim($output',');
echo $output;
?>

It would output:

The difference is: 2 years, 9 months, 3 weeks, 4 days, 5 hours, 25 minutes, 4 seconds

2008-09-20

Calculate Age: One-Liner Fun

by Charles — Categories: PHP — Tags: , 1 Comment

Here’s a little one-liner I thought up today for this PHPBuilder forum thread. It’s purpose is to calculate someone’s age when you know the year, month, and day of their birth (integer values). In this snippet it is assumed that $year, $month, and $day hold the integer values for the birthday of interest.

$today = time();
for($yr = $year, $age = -1; mktime(0,0,0,$month,$day,$yr) < $today; $yr++, $age++);
echo $age;

This utilizes the often ignored fact that you can use comma-separated statements for the first and third expressions in the for loop definition list.

© 2012 PHP Musings All rights reserved - Wallow theme v0.46.4 by ([][]) TwoBeers - Powered by WordPress - Have fun!