"Time Ago" Calculation


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.