Time Ago Function in PHP

Here’s a lightweight PHP function which accepts a date as a parameter and converts it into “sometime age” output.

Read Also: How to enable mod_rewrite in Ubuntu

function time_ago($date) {
    if (empty($date)) {
        return "Please enter a date!";
    }
    $duration_in = [
        "second", 
        "minute", 
        "hour", 
        "day", 
        "week", 
        "month", 
        "year", 
        "decade"
    ];
    $len = [
        "60", 
        "60", 
        "24", 
        "7", 
        "4.35", 
        "12", 
        "10"
    ];
    $now = time();
    $unixDate = strtotime($date);

    if (empty($unixDate)) {
        return "Please enter a valid date!";
    }

    if ($now > $unixDate) {
        $diff = $now - $unixDate;
        $tense = "ago";
    } else {
        $diff = $unixDate - $now;
        $tense = "from now";
    }
    for ($j = 0; $diff >= $len[$j] && $j < count($len) - 1; $j++) {
        $difference /= $len[$j];
    }
    $diff = round($diff);
    if ($diff != 1) {
        $duration_in[$j].= "s";
    }
    return "$diff $duration_in[$j] {$tense}";
}

Usage:

echo time_ago($date);

Source: http://stackoverflow.com/a/18891474

0 Comments

Leave a Comment.