Home >Backend Development >PHP Tutorial >How to Convert a Timestamp to 'Time Ago' in PHP?
Convert Timestamp to Time Ago in PHP: A Comprehensive Guide
To convert a timestamp to a human-readable format such as "3 minutes ago" in PHP, we can use the convenient function time_elapsed_string(). Let's explore its usage and delve into its implementation.
Function Usage:
The time_elapsed_string() function takes a datetime string as its first argument, representing the timestamp you want to convert. Optionally, you can specify true as the second argument to display the full elapsed time in years, months, weeks, days, hours, minutes, and seconds.
For example:
echo time_elapsed_string('2013-05-01 00:22:35'); echo time_elapsed_string('@1367367755'); # timestamp input echo time_elapsed_string('2013-05-01 00:22:35', true);
Function Output:
The function returns a string representing the elapsed time in a user-friendly format:
4 months ago 4 months ago 4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago
Implementation:
Let's examine the implementation of the time_elapsed_string() function:
function time_elapsed_string($datetime, $full = false) { $now = new DateTime; $ago = new DateTime($datetime); $diff = $now->diff($ago); $diff->w = floor($diff->d / 7); $diff->d -= $diff->w * 7; $string = array( 'y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ); foreach ($string as $k => &$v) { if ($diff->$k) { $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : ''); } else { unset($string[$k]); } } if (!$full) $string = array_slice($string, 0, 1); return $string ? implode(', ', $string) . ' ago' : 'just now'; }
This function first creates instances of DateTime for the current time ($now) and the provided timestamp ($ago). It then calculates the difference between the two using the diff() method, which returns a DateInterval object containing the elapsed time in various units.
The function modifies the days component of the $diff object to account for weeks and removes zero-value components from the $string array. If the $full parameter is true, the full array is used for the output; otherwise, only the first component is selected.
Finally, the function converts the $string array into a human-readable string by joining the components with commas and appending "ago." If the elapsed time is less than a minute, it returns "just now."
By understanding the implementation of this handy function, you can effectively convert timestamps to time ago strings in your PHP applications, making it easier for users to comprehend date information.
The above is the detailed content of How to Convert a Timestamp to 'Time Ago' in PHP?. For more information, please follow other related articles on the PHP Chinese website!