Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to show "5 minutes ago"

Short answer

Calculate the difference in seconds and pick a unit:

<?php
 
function timeAgo(DateTimeImmutable $date, DateTimeImmutable $now): string
{
    $seconds = $now->getTimestamp() - $date->getTimestamp();
 
    return match (true) {
        $seconds < 60 => 'just now',
        $seconds < 3600 => intdiv($seconds, 60) . ' min ago',
        $seconds < 86400 => intdiv($seconds, 3600) . ' h ago',
        default => intdiv($seconds, 86400) . ' d ago',
    };
}
 
$now = new DateTimeImmutable('2026-03-15 12:00');
 
echo timeAgo(new DateTimeImmutable('2026-03-15 11:55'), $now), "\n";
echo timeAgo(new DateTimeImmutable('2026-03-15 09:00'), $now), "\n";
echo timeAgo(new DateTimeImmutable('2026-03-10 12:00'), $now);

Output:

5 min ago
3 h ago
5 d ago

The current time

In real code the second argument is new DateTimeImmutable(). Having the current time as a parameter rather than inside the function makes it testable.

Functions used in this recipe

  • DateTimeImmutable — A date and time object that cannot be changed: every operation returns a new object.
  • date_diff — Calculates the difference between two dates.
  • intdiv — Performs integer division.

Thanks for reading!

Donate to the site — we work hard for you.