Posted By

LuckyShot on 06/09/10


Tagged

php date relative


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

karp13
beertigger
IMPGTX


PHP - Relative date function (2 minutes ago, 3 days ago...)


 / Published in: PHP
 

URL: http://xaviesteve.com/category/web-design/php/

Gets seconds and returns it like Facebook/Twitter style: "2 minutes ago", "9 hours ago", etc... The script actually returns "1 minute", "17 days"... so that you can customize it: "3 seconds ago", "in 1 minute", "will take 4 days", etc.

  1. function relativedate($secs) {
  2. $second = 1;
  3. $minute = 60;
  4. $hour = 60*60;
  5. $day = 60*60*24;
  6. $week = 60*60*24*7;
  7. $month = 60*60*24*7*30;
  8. $year = 60*60*24*7*30*365;
  9.  
  10. if ($secs <= 0) { $output = "now";
  11. }elseif ($secs > $second && $secs < $minute) { $output = round($secs/$second)." second";
  12. }elseif ($secs >= $minute && $secs < $hour) { $output = round($secs/$minute)." minute";
  13. }elseif ($secs >= $hour && $secs < $day) { $output = round($secs/$hour)." hour";
  14. }elseif ($secs >= $day && $secs < $week) { $output = round($secs/$day)." day";
  15. }elseif ($secs >= $week && $secs < $month) { $output = round($secs/$week)." week";
  16. }elseif ($secs >= $month && $secs < $year) { $output = round($secs/$month)." month";
  17. }elseif ($secs >= $year && $secs < $year*10) { $output = round($secs/$year)." year";
  18. }else{ $output = " more than a decade ago"; }
  19.  
  20. if ($output <> "now"){
  21. $output = (substr($output,0,2)<>"1 ") ? $output."s" : $output;
  22. }
  23. return $output;
  24. }
  25.  
  26.  
  27.  
  28. echo relativedate(60); // 1 minute

Report this snippet  

You need to login to post a comment.