Re: difference in time

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Lamp Lists wrote:
hi to all!
  on one eZine site, I have to show when the article is posted but as difference from NOW. like "posted 32 minutes ago", or "posted 5 days ago".
is there already sucha php/mysql function? thanks.

Hi,

I don't know about existing functions but you can use this:

   function time_to_units($time) {

       $years = floor($time / 60 / 60 / 24/ 365);
       $time -= $years * 60 * 60 * 24 * 365;
       $months = floor($time / 60 / 60 / 24 / 30);
       $time -= $months * 60 * 60 * 24 * 30;
       $weeks = floor($time / 60 / 60 / 24 / 7);
       $time -= $weeks * 60 * 60 * 24 * 7;
       $days = floor($time / 60 / 60 / 24);
       $time -= $days * 60 * 60 * 24;
       $hours = floor($time / 60 / 60);
       $time -= $hours * 60 * 60;
       $minutes = floor($time / 60);
       $time -= $minutes * 60;
       $seconds = $time;
       $amount = 0;
       $unit = '';

       if ($years > 0) {

           $amount = $years;
           $unit = ' year';

           if ($years > 1) {

               $unit.= 's ';
           }
       }
       elseif ($months > 0) {

           $amount = $months;
           $unit = ' month';

           if ($months > 1) {

               $unit.= 's ';
           }
       }
       elseif ($weeks > 0) {

           $amount = $weeks;
           $unit = ' week';

           if ($weeks > 1) {

               $unit.= 's ';
           }
       }
       elseif ($days > 0) {

           $amount = $days;
           $unit = ' day';

           if ($days > 1) {

               $unit.= 's ';
           }
       }
       elseif ($hours > 0) {

           $amount = $hours;
           $unit = ' hour';

           if ($hours > 1) {

               $unit.= 's ';
           }
       }
       elseif ($minutes > 0) {

           $amount = $minutes;
           $unit = ' minute';

           if ($minutes > 1) {

               $unit.= 's ';
           }
       }
       elseif ($seconds > 0) {

           $amount = $seconds;
           $unit = ' second';

           if ($seconds > 1) {

               $unit.= 's ';
           }
       }

       return $amount.$unit;
   }

$posted = ; // some timestamp in the past
$now = time(); // as current as possible
$diff = ($now - $posted);

echo "posted ".time_to_units($diff)." ago";

I hope this helps ;-)
--

Aschwin Wesselius

/'What you would like to be done to you, do that to the other....'/

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux