1

Does anyone if php has built in functionally to do this?

Thanks

Rog888
  • 71
  • 1
  • 4
  • possible duplicate of [Converting timestamp to time ago in php e.g 1 day ago, 2 days ago...](http://stackoverflow.com/questions/1416697/converting-timestamp-to-time-ago-in-php-e-g-1-day-ago-2-days-ago) as [lots more](http://stackoverflow.com/search?q=php+date+days+ago) – ajreal Dec 21 '10 at 06:10
  • Just found a function that does exactly what I needed http://www.php.net/manual/en/function.time.php#89415 – Rog888 Dec 21 '10 at 06:09
  • Not natively, but my answer to [a similar question](https://stackoverflow.com/questions/4394161/4394181#4394181) will probably be useful to you. – El Yobo Dec 21 '10 at 06:09

2 Answers2

1

There is no built in function for this....but the following function will do it.

<?php
function nicetime($date)
{
    if(empty($date)) {
        return "No date provided";
    }

    $periods         = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
    $lengths         = array("60","60","24","7","4.35","12","10");

    $now             = time();
    $unix_date         = strtotime($date);

       // check validity of date
    if(empty($unix_date)) {   
        return "Bad date";
    }

    // is it future date or past date
    if($now > $unix_date) {   
        $difference     = $now - $unix_date;
        $tense         = "ago";

    } else {
        $difference     = $unix_date - $now;
        $tense         = "from now";
    }

    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
        $difference /= $lengths[$j];
    }

    $difference = round($difference);

    if($difference != 1) {
        $periods[$j].= "s";
    }

    return "$difference $periods[$j] {$tense}";
}

$date = "2009-03-04 17:45";
$result = nicetime($date); // 2 days ago

?>
GitaarLAB
  • 14,536
  • 11
  • 60
  • 80
rajmohan
  • 1,618
  • 1
  • 15
  • 36
-1
$date = "2009-03-04 17:45";
$result = nicetime($date);

will only return 2 Days Ago

But if u want to get results like 1 sec ago, 10 secs ago, u also need to add seconds in $date

$date = "2009-03-04 17:45:20";
$result = nicetime($date);

So when u add a fresh db entry and u refresh the page immediately, u wil get the result as 1 sec ago