Home >Backend Development >PHP Tutorial >How Can I Convert a Timestamp to a 'Time Ago' Format in PHP?
Converting Timestamps to Time Ago Format in PHP
To convert a timestamp in the format 2009-09-12 20:57:19 to a human-readable time ago format, such as "3 minutes ago," a modification to the provided PHP script is necessary.
Step 1: Converting the Timestamp
The first step is to convert the given timestamp to a Unix timestamp, which represents the number of seconds since January 1, 1970 UTC. To do this, use the following code:
$timestamp = strtotime('2009-09-12 20:57:19');
Step 2: Modifying the Script
The provided script, _ago, takes a Unix timestamp as its first parameter. Replace the first few lines of the script with the following:
function time_ago($timestamp, $rcs = 0) { $cur_tm = time(); $dif = $cur_tm - $timestamp;
Step 3: Calling the Modified Script
Example: To get the time ago representation for the given timestamp, call the modified script as follows:
echo time_ago($timestamp);
Example Output:
The script will output a human-readable time ago representation, depending on the time difference between the current time and the given timestamp. For example, if the given timestamp is 3 minutes in the past, it will output "3 minutes ago."
The above is the detailed content of How Can I Convert a Timestamp to a 'Time Ago' Format in PHP?. For more information, please follow other related articles on the PHP Chinese website!