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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Ordering units largest-first lets the first match determine the coarsest sensible label.
- 2The null coalescing assignment operator gives a clean default for optional arguments.
- 3Integer division truncates, so a non-zero quotient signals the biggest unit that fits.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
php
class TwoFactorController extends Controller { public function show(Request $request): View|RedirectResponse {
Two-factor auth challenge flow in Laravel
authentication
two-factor
middleware
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-timeago-helper-in-php-explained-php-a326/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.