Php date to word convert (like 4 days ago )


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



Copy this code and paste it in your HTML
  1. /* Change the following constants to suit your language */
  2.  
  3. define('STRING_TODAY', "today");
  4. define('STRING_YESTERDAY', "yesterday");
  5. define('STRING_DAYS', "%d days ago");
  6. define('STRING_WEEK', "1 week ago");
  7. define('STRING_WEEKS', "%d weeks ago");
  8.  
  9. /* Change the following date format to your taste */
  10. define('DATE_FORMAT', "m-d-Y");
  11.  
  12. /* The functions takes the date as a timestamp */
  13. function DateToWords($time)
  14. {
  15.  
  16. $_word = "";
  17.  
  18. /* Get the difference between the current time
  19.   and the time given in days */
  20. $days = intval((time() - $time) / 86400);
  21.  
  22. /* If some forward time is given return error */
  23. if($days < 0) {
  24. return -1;
  25. }
  26.  
  27. switch($days) {
  28. case 0: $_word = STRING_TODAY;
  29. break;
  30. case 1: $_word = STRING_YESTERDAY;
  31. break;
  32. case ($days >= 2 && $days <= 6):
  33. $_word = sprintf(STRING_DAYS, $days);
  34. break;
  35. case ($days >= 7 && $days < 14):
  36. $_word= STRING_WEEK;
  37. break;
  38. case ($days >= 14 && $days <= 365):
  39. $_word = sprintf(STRING_WEEKS, intval($days / 7));
  40. break;
  41. default : return date(DATE_FORMAT, $time);
  42.  
  43. }
  44.  
  45. return $_word;
  46. }

URL: http://www.codediesel.com/php/printing-relative-dates-in-php/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.