DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Relative Date

04.19.2005
| 14890 views |
  • submit to reddit
        This function takes a time and returns a relative date string (it does, however, ignore the time of day). For instance: "yesterday", "in 2 days", "1 day ago", "March 12", or "May 5, 1992".

function relative_date($time) {
    $today = strtotime(date('M j, Y'));
    $reldays = ($time - $today)/86400;
    if ($reldays >= 0 && $reldays < 1) {
        return 'today';
    } else if ($reldays >= 1 && $reldays < 2) {
        return 'tomorrow';
    } else if ($reldays >= -1 && $reldays < 0) {
        return 'yesterday';
    }
    if (abs($reldays) < 7) {
        if ($reldays > 0) {
            $reldays = floor($reldays);
            return 'in ' . $reldays . ' day' . ($reldays != 1 ? 's' : '');
        } else {
            $reldays = abs(floor($reldays));
            return $reldays . ' day'  . ($reldays != 1 ? 's' : '') . ' ago';
        }
    }
    if (abs($reldays) < 182) {
        return date('l, F j',$time ? $time : time());
    } else {
        return date('l, F j, Y',$time ? $time : time());
    }
}
    

Comments

Snippets Manager replied on Wed, 2009/09/23 - 6:32am

I am hunting for an efficient age computation algorithm to use on my community site's user profiles, and this snippet looks like a probable solution. But I suspect that it doesn't take leap years into account. Right?