octavian-filipciuc
7/24/2014 - 6:39 PM

Convert time to time ago

Convert time to time ago

Use it: <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?>
function time_ago($then) {
    $diff = time() - strtotime($then);

    $second = 1;
    $minute = $second * 60;
    $hour = $minute * 60;
    $day = $hour * 24;
    $week = $day * 7;

    if (is_nan($diff) || $diff < 0) {
        return ""; // return blank string if unknown
    }

    if ($diff < $second * 2) {
        // within 2 seconds
        return "right now";
    }

    if ($diff < $minute) {
        return floor($diff / $second) . " seconds ago";
    }

    if ($diff < $minute * 2) {
        return "about 1 minute ago";
    }

    if ($diff < $hour) {
        return floor($diff / $minute) . " minutes ago";
    }

    if ($diff < $hour * 2) {
        return "about 1 hour ago";
    }

    if ($diff < $day) {
        return floor($diff / $hour) . " hours ago";
    }

    if ($diff > $day && $diff < $day * 2) {
        return "yesterday";
    }

    if ($diff < $day * 365) {
        return floor($diff / $day) . " days ago";
    }

    return "over a year ago";
}