Days ago function


 / Published in: PHP
 

URL: http://pat.b22222.com

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 :)

  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. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: headzoo on June 15, 2008

I ended up changing the code to this:

public static function getHowLongAgo($date, $display = array('Year', 'Month', 'Day', 'Hour', 'Minute', 'Second'), $ago = 'Ago')
{
    $date = getdate(strtotime($date));
    $current = getdate();
    $p = array('year', 'mon', 'mday', 'hours', 'minutes', 'seconds');
    $factor = array(0, 12, 30, 24, 60, 60);

    for ($i = 0; $i < 6; $i++) {
        if ($i > 0) {
            $current[$p[$i]] += $current[$p[$i - 1]] * $factor[$i];
            $date[$p[$i]] += $date[$p[$i - 1]] * $factor[$i];
        }
        if ($current[$p[$i]] - $date[$p[$i]] > 1) {
            $value = $current[$p[$i]] - $date[$p[$i]];
            return $value . ' ' . $display[$i] . (($value != 1) ? 's' : '') . ' ' . $ago;
        }
    }

    return '';
}

PHP's own getdate() does what your datetoarr() function does. Plus I changed a few other things.

You need to login to post a comment.