Days ago function


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

Takes a date and returns a string describing how long ago that date was. examples: 3 seconds ago, 5 days ago, 2 years ago, you get the idea :)


Copy this code and paste it in your HTML
  1. // convert a date into a string that tells how long ago that date was.... eg: 2 days ago, 3 minutes ago.
  2. function ago($d) {
  3. $c = getdate();
  4. $p = array('year', 'mon', 'mday', 'hours', 'minutes', 'seconds');
  5. $display = array('year', 'month', 'day', 'hour', 'minute', 'second');
  6. $factor = array(0, 12, 30, 24, 60, 60);
  7. $d = datetoarr($d);
  8. for ($w = 0; $w < 6; $w++) {
  9. if ($w > 0) {
  10. $c[$p[$w]] += $c[$p[$w-1]] * $factor[$w];
  11. $d[$p[$w]] += $d[$p[$w-1]] * $factor[$w];
  12. }
  13. if ($c[$p[$w]] - $d[$p[$w]] > 1) {
  14. return ($c[$p[$w]] - $d[$p[$w]]).' '.$display[$w].'s ago';
  15. }
  16. }
  17. return '';
  18. }
  19.  
  20. // you can replace this if need be. This converts my dates returned from a mysql date string into
  21. // an array object similar to that returned by getdate().
  22. function datetoarr($d) {
  23. preg_match("/([0-9]{4})(\\-)([0-9]{2})(\\-)([0-9]{2}) ([0-9]{2})(\\:)([0-9]{2})(\\:)([0-9]{2})/", $d, $matches);
  24. return array(
  25. 'seconds' => $matches[10],
  26. 'minutes' => $matches[8],
  27. 'hours' => $matches[6],
  28. 'mday' => $matches[5],
  29. 'mon' => $matches[3],
  30. 'year' => $matches[1],
  31. );
  32. }

URL: http://pat.b22222.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.