php 36 lines · 6 steps

Building a timeAgo helper in PHP

Convert a timestamp difference into a human phrase like "3 days ago" by walking descending time units.

Explained by highlit
1<?php
2 
3function timeAgo(DateTimeInterface $past, ?DateTimeInterface $now = null): string
4{
5 $now ??= new DateTimeImmutable();
6 $diff = $now->getTimestamp() - $past->getTimestamp();
7 
8 if ($diff < 0) {
9 return 'in the future';
10 }
11 
12 if ($diff < 10) {
13 return 'just now';
14 }
15 
16 $units = [
17 ['year', 31536000],
18 ['month', 2592000],
19 ['week', 604800],
20 ['day', 86400],
21 ['hour', 3600],
22 ['minute', 60],
23 ['second', 1],
24 ];
25 
26 foreach ($units as [$label, $seconds]) {
27 $value = intdiv($diff, $seconds);
28 
29 if ($value > 0) {
30 $plural = $value === 1 ? $label : $label . 's';
31 return sprintf('%d %s ago', $value, $plural);
32 }
33 }
34 
35 return 'just now';
36}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Ordering units largest-first lets the first match determine the coarsest sensible label.
  2. 2The null coalescing assignment operator gives a clean default for optional arguments.
  3. 3Integer division truncates, so a non-zero quotient signals the biggest unit that fits.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a timeAgo helper in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code