Convert Timestamp to Time Ago Format in PHP (Display Relative Time Format)

Many web applications like Facebook, Reddit, YouTube, and GitHub use the time ago format (also known as relative time format) to display the time when content was created. Learn how to convert a timestamp to a time ago format in PHP applications in a simple way.

Convert Timestamp to Time Ago Format in PHP

Displaying a date and time in a relative format in web applications improves the user experience because humans can understand it more quickly. It also saves visual space compared to showing a complete date and time, which makes interfaces cleaner for users, especially on mobile devices. This post demonstrates how to convert timestamp to time ago format in PHP with one custom function.

 

Convert Timestamp to 'Time Ago' Format in PHP (Custom Function)

A PHP application can have users from different locations and time zones. Showing the time in a relative format avoids confusion for users from different time zones. We can achieve this in PHP by creating a custom function that accepts a Unix timestamp as a parameter, calculates the difference to the current time, and returns a relative time format as a string. The function logic is as follows:

  • Create a function with the name to_time_ago_format().
  • Declare a variable $ago_from_now to store the difference between the current time and the provided timestamp using the time() function.
  • Check if $ago_from_now is less than one, then the difference is less than one second. Return "Just now" from here and skip further code execution.
  • Declare a variable $time_ago to store the time ago string and initially assign it a NULL value.
  • Declare variables for interval units for second, minute, hour, week, day, month, and year.
  • Create an associative array $time_intervals to store interval units as keys and values as desired or relevant string values for each interval unit.
  • Sort the $time_intervals array in descending order so we have the largest key value as the first entry and the smallest key as the last entry. This is important to return the correct string. You can also declare this array in reverse order to skip sorting.
  • Loop through each entry in the $time_intervals array and check if $ago_from_now is greater than or equal to the interval unit key in the array.
  • If the above condition matches, then assign the correct string to the $time_ago variable.
  • Finally, return the $time_ago string from the function.
/**
* @param int $timestamp
* @return string|null
*
*/
function to_time_ago_format(int $timestamp): ?string
{
$ago_from_now = time() - $timestamp;

// If time difference is less than one second, return "Just now"
if ($ago_from_now < 1) {
return 'Just now';
}

$time_ago = NULL;

// Define the time intervals (in seconds)
$second = 1;
$minute = 60 * $second;
$hour = 60 * $minute;
$day = 24 * $hour;
$week = 7 * $day;
$month = 30 * $day;
$year = 12 * $month;

// Create an array of time units and strings needed for specific unit
$time_intervals = [
$second => 'second',
$minute => 'minute',
$hour => 'hour',
$day => 'day',
$week => 'week',
$month => 'month',
$year => 'year',
];

// Sort array in descending order by keys
krsort($time_intervals);

foreach ($time_intervals as $time => $string) {
if ($ago_from_now >= $time) {
$unit = floor($ago_from_now / $time);

$time_ago = sprintf('%d %s%s %s', $unit, $string, $unit > 1 ? 's' : '', 'ago');
break;
}
}

return $time_ago;
}

Usage of The Time Ago Function

This function will now return the human-readable time ago string for a given timestamp. The function accepts a timestamp as a parameter, so the date-time string first needs to be converted to a timestamp using PHP's strtotime() function. The function can be used as in the following code snippet:

$time_ago = to_time_ago_format(strtotime('2020-04-03 02:35:12'));

echo $time_ago;
 

Date and Time Conversion Examples in PHP

The following is an example of how our function will return a relative time string for different timestamp parameters:

to_time_ago_format(strtotime('now')); // Just Now
to_time_ago_format(strtotime('-2 seconds')); // 2 seconds ago
to_time_ago_format(strtotime('-2 minutes')); // 2 minutes ago
to_time_ago_format(strtotime('-2 hours')); // 2 hours ago
to_time_ago_format(strtotime('-2 days')); // 2 days ago
to_time_ago_format(strtotime('-2 weeks')); // 2 weeks ago
to_time_ago_format(strtotime('-2 months')); // 2 months ago
to_time_ago_format(strtotime('-2 years')); // 2 years ago

Converting timestamps to a human-readable format is a simple and useful way to improve user experience and make it easier for users to read the time. We demonstrated how we can convert a relative time format using the time() and strtotime() functions.