Search code examples
phptimetimeago

PHP timeAgo to return In X days if timestamp is in the future


I have this PHP function that returns timeAgo from a timestamp.

function time_ago($time) {
    $periods = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade');
    $lengths = array('60', '60', '24', '7', '4.35', '12', '10');
    $now = time();
    $difference     = $now - $time;
    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] . ' ago';
}

Now if the timestamp is greater than NOW, it will return "47 years ago".

How to make it return "In 3 days, 5 hours, 16 minutes" if timestamp is greater than NOW?

Thanks.


Solution

  • function time_ago($time) {
        $periods = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade');
        $lengths = array('60', '60', '24', '7', '4.35', '12', '10');
        $now = time();
        // if($now > $time) {
        $difference     = $now - $time;
        if ($now < $time) {
                $difference = $time - $now;
        }
        for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
            $difference /= $lengths[$j];
        }
        $difference = round($difference);
        if ($difference != 1) {
            $periods[$j] .= 's';
        }
        //if ($now > $time) {
        $text = $difference . ' ' . $periods[$j] . ' ago';
        } elseif ($now < $time) {
                $text = 'In ' . $difference . ' ' . $periods[$j];
        } 
    
        return $text;
    }
    

    This might work. Although I don't see a loop for adding the different periods, just the first match. And even then you probably forgot to break the loop after a match.

    Edit: You're probably better off using the DateTime::diff function, which mixed with the "format" function automatizes this process for you, more accurately and efficiently (since your loop is incomplete and it only processes the last iteration in the array)

    http://php.net/manual/en/datetime.diff.php