Home >Backend Development >PHP Tutorial >How Can I Calculate and Display Elapsed Time in a Human-Readable Format (e.g., 'xx Minutes Ago') in PHP?

How Can I Calculate and Display Elapsed Time in a Human-Readable Format (e.g., 'xx Minutes Ago') in PHP?

DDD
DDDOriginal
2024-12-09 05:36:09783browse

How Can I Calculate and Display Elapsed Time in a Human-Readable Format (e.g.,

Calculating Time Elapsed Since a Date Time in PHP

Determining the elapsed time since a given date and time, such as "2010-04-28 17:25:43," is a common task in programming. The goal is to generate a user-friendly output indicating the time difference in a concise format like "xx Minutes Ago" or "xx Days Ago."

Personalized Time Representation

While converting the date string to a time object is a necessary step, many answers overlook the desired output format. To achieve the "xx Minutes Ago" format, a customized function is required.

Humanizing Time Calculations

One effective approach is to utilize the humanTiming() function, which calculates the time difference between the current time and the provided timestamp. Within the function:

  1. The time difference (in seconds) is calculated by subtracting the timestamp from the current time.
  2. An array of time units and their corresponding textual representations is defined.
  3. The function iterates through the array and checks which unit is applicable based on the time difference.
  4. The number of units that have passed is determined, and the appropriate textual representation is returned.

Example Usage

To use the function:

$time = strtotime('2010-04-28 17:25:43');

echo 'event happened '.humanTiming($time).' ago';

Output

Depending on the time difference, the output will be in the desired format, such as:

  • "event happened 4 days ago"
  • "event happened 1 minute ago"

The above is the detailed content of How Can I Calculate and Display Elapsed Time in a Human-Readable Format (e.g., 'xx Minutes Ago') in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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