We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

jaytee on 02/06/08


Tagged

time date


Versions (?)


Who likes this?

5 people have marked this snippet as a favorite

adix
jimmayes
axthos
romanos
tikitakfire


Relative Time


Published in: PHP 


Takes a date and returns the relative time (e.g. "10 minutes ago", "3 weeks ago", etc.) Past four weeks, it just returns the date in the form "January 1, 2008".

  1. function plural($num) {
  2. if ($num != 1)
  3. return "s";
  4. }
  5.  
  6. function getRelativeTime($date) {
  7. $diff = time() - strtotime($date);
  8. if ($diff<60)
  9. return $diff . " second" . plural($diff) . " ago";
  10. $diff = round($diff/60);
  11. if ($diff<60)
  12. return $diff . " minute" . plural($diff) . " ago";
  13. $diff = round($diff/60);
  14. if ($diff<24)
  15. return $diff . " hour" . plural($diff) . " ago";
  16. $diff = round($diff/24);
  17. if ($diff<7)
  18. return $diff . " day" . plural($diff) . " ago";
  19. $diff = round($diff/7);
  20. if ($diff<4)
  21. return $diff . " week" . plural($diff) . " ago";
  22. return "on " . date("F j, Y", strtotime($date));
  23. }

Report this snippet 

You need to login to post a comment.