Skip to main content

Tutorial: Facebook Style time stamp using PHP

Lovell Felix 1 min read

Archive note: the tools and versions have moved on. I have kept this entry because the debugging path and the underlying constraint may still be useful.

This function returns the difference between two dates in a human friendly string format. For instance, the values returned are seconds ago, 50 minutes ago, 7 hours ago, a day ago, weeks ago, years ago, and so on. It's similar to the approach used by many social media websites.

Syntax $time = strtotime(YYYY-MM-DD HH:MM:SS)

Example:


$time = strtotime(''2010/09/10 10:00:00'') => "- 3 days ago"

//The default time units are:

$tokens = array ( 31536000 => ''year'', 2592000 => ''month'', 604800 => ''week'', 86400 => ''day'', 3600 => ''hour'', 60 => ''minute'', 1 => ''second'' ); 

//The text will be automatically de-pluralized if, say there is only 1 year.

foreach ($tokens as $unit => $text) {
if ($time < $unit) continue; $numberOfUnits = floor($time / $unit);
return $numberOfUnits.'' ''.$text.(($numberOfUnits>1)?''s'':'''');
}

The complete project can be download from my Github Repository

About the author

Lovell Felix

Infrastructure and reliability engineer working on Linux platforms, configuration delivery, and deployment safety at fleet scale.

@lovellfelix

More notes