This PHP function time_ago($timestamp) is used to convert a date/time string into a human-readable format like “2 hours ago”, “1 week ago”, etc. Let’s break it down step by step:
function time_ago($timestamp)
$timestamp
(a string, like '2025-04-06 10:00:00'
).$current_time = time(); // Current UNIX timestamp
$time_diff = $current_time - strtotime($timestamp); // Difference in seconds
$seconds = $time_diff;
$minutes = round($seconds / 60);
$hours = round($seconds / 3600);
$days = round($seconds / 86400);
$weeks = round($seconds / 604800);
$months = round($seconds / 2629440);
$years = round($seconds / 31553280);
This section converts the time difference into:
This part checks the time range and returns the correct string:
if ($seconds <= 60) {
return "Just now";
} elseif ($minutes <= 60) {
return ($minutes == 1) ? "1 minute ago" : "$minutes minutes ago";
}
So the function returns:
function time_ago($timestamp) {
$current_time = time();
$time_diff = $current_time - strtotime($timestamp);
$seconds = $time_diff;
$minutes = round($seconds / 60);
$hours = round($seconds / 3600);
$days = round($seconds / 86400);
$weeks = round($seconds / 604800);
$months = round($seconds / 2629440);
$years = round($seconds / 31553280);
if ($seconds <= 60) {
return "Just now";
} elseif ($minutes <= 60) {
return ($minutes == 1) ? "1 minute ago" : "$minutes minutes ago";
} elseif ($hours <= 24) {
return ($hours == 1) ? "1 hour ago" : "$hours hours ago";
} elseif ($days <= 7) {
return ($days == 1) ? "1 day ago" : "$days days ago";
} elseif ($weeks <= 4.3) {
return ($weeks == 1) ? "1 week ago" : "$weeks weeks ago";
} elseif ($months <= 12) {
return ($months == 1) ? "1 month ago" : "$months months ago";
} else {
return ($years == 1) ? "1 year ago" : "$years years ago";
}
}
If current time is 2025-04-06 12:00:00 and you pass:
time_ago("2025-04-06 11:45:00");
Then: