PHP

Human-Readable "Time Ago"

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Convert a timestamp into a short relative phrase: "just now", "5 minutes ago", "3 days ago". Falls back to an absolute date once the delta exceeds a year.
PHP
Raw
<?php
function timeAgo(int|string $time): string {
    $t = is_int($time) ? $time : strtotime($time);
    $d = time() - $t;
    if ($d < 60)         return 'just now';
    if ($d < 3600)       return intdiv($d, 60)    . 'm ago';
    if ($d < 86400)      return intdiv($d, 3600)  . 'h ago';
    if ($d < 604800)     return intdiv($d, 86400) . 'd ago';
    if ($d < 2_592_000)  return intdiv($d, 604800)   . 'w ago';
    if ($d < 31_536_000) return intdiv($d, 2_592_000)  . 'mo ago';
    return date('M j, Y', $t);
}

echo timeAgo(time() - 30);          // just now
echo timeAgo(time() - 90);          // 1m ago
echo timeAgo(time() - 7200);        // 2h ago
echo timeAgo(time() - 86400 * 400); // Mar 5, 2024
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.