Home > Backend Development > PHP Tutorial > How Can I Convert a Timestamp to a 'Time Ago' Format in PHP?

How Can I Convert a Timestamp to a 'Time Ago' Format in PHP?

DDD
Release: 2024-12-21 18:17:17
Original
450 people have browsed it

How Can I Convert a Timestamp to a

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');
Copy after login

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;
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template