Posted By

saturngod on 07/17/10


Tagged

time facebook


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

IMPGTX
Some0ne
Nix
manavecplan
Net-Freak


Facebook Style time ago


 / Published in: PHP
 

URL: http://php.net/manual/en/function.time.php

  1. <?php
  2. function nicetime($date)
  3. {
  4. if(empty($date)) {
  5. return "No date provided";
  6. }
  7.  
  8. $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
  9. $lengths = array("60","60","24","7","4.35","12","10");
  10.  
  11. $now = time();
  12. $unix_date = strtotime($date);
  13.  
  14. // check validity of date
  15. if(empty($unix_date)) {
  16. return "Bad date";
  17. }
  18.  
  19. // is it future date or past date
  20. if($now > $unix_date) {
  21. $difference = $now - $unix_date;
  22. $tense = "ago";
  23.  
  24. } else {
  25. $difference = $unix_date - $now;
  26. $tense = "from now";
  27. }
  28.  
  29. for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
  30. $difference /= $lengths[$j];
  31. }
  32.  
  33. $difference = round($difference);
  34.  
  35. if($difference != 1) {
  36. $periods[$j].= "s";
  37. }
  38.  
  39. return "$difference $periods[$j] {$tense}";
  40. }
  41.  
  42. $date = "2009-03-04 17:45";
  43. $result = nicetime($date); // 2 days ago
  44.  
  45. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: dxlwebs on November 2, 2010

my date comes from php echo date("D-M-Y H:i:s", $rows->date_add); how would i implement this?

Posted By: dxlwebs on November 2, 2010

i got this working

Posted By: KenanRecebli on January 5, 2014

i dont see who is the author of this script, but i want to say him a lot thanks and would like to performance to him (and to everybody) a modification of this script.. i have modified it a bit and it is absolutely like on fb.. new "featchures" are:

instead - * 1-59 seconds, minutes, hours - nothing modified; * 1 day ago: Yesterday at --:-- * 2-7 days ago: Monday (or other day of the week) at --:-- * 1 week ago etc.: Dec 27, 2013 at 22:06 (for example)

You need to login to post a comment.