Posted By

mike_fowler on 03/30/11


Tagged

time ago


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

nbegiter
Some0ne


"Time Ago" Calculation


 / Published in: PHP
 

URL: http://css-tricks.com/snippets/php/time-ago-function/

Accepts a UNIX timestamp, like the result of time(), and formats it into "# (days/months/etc) ago"

  1. function ago($time)
  2. {
  3. $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
  4. $lengths = array("60","60","24","7","4.35","12","10");
  5.  
  6. $now = time();
  7.  
  8. $difference = $now - $time;
  9. $tense = "ago";
  10.  
  11. for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
  12. $difference /= $lengths[$j];
  13. }
  14.  
  15. $difference = round($difference);
  16.  
  17. if($difference != 1) {
  18. $periods[$j].= "s";
  19. }
  20.  
  21. return "$difference $periods[$j] 'ago' ";
  22. }

Report this snippet  

You need to login to post a comment.