분류 php

PHP : Facebook Style time ago

컨텐츠 정보

  • 조회 739 (작성일 )

본문

  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. ?>
php