Home > Backend Development > PHP Tutorial > How to Calculate and Display Time Elapsed Since a Date in PHP?

How to Calculate and Display Time Elapsed Since a Date in PHP?

Barbara Streisand
Release: 2024-12-17 02:03:25
Original
284 people have browsed it

How to Calculate and Display Time Elapsed Since a Date in PHP?

Finding the Time Elapsed Since a Date Time in PHP

Determining the time elapsed since a specific date and time is a common task in programming. This question explores how to accomplish this in PHP.

Converting to a Time Value

The first step is to convert the given date and time string ("2010-04-28 17:25:43") into a time value using the strtotime() function.

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

Calculating the Time Difference

Next, calculate the time difference between the current time and the time stored in $time. This value will be a timestamp representing the elapsed time.

$timeDifference = time() - $time;
Copy after login

Converting to Human-Readable Format

To display the elapsed time in a human-readable format (e.g., "xx Minutes Ago"), use the humanTiming() function presented in the answer:

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

humanTiming() Function

The function takes a time value as input and generates a human-readable string representing the elapsed time. It uses an array of time units and their corresponding text descriptions to determine the most appropriate time unit to display.

The output of the humanTiming() function will follow the format: ago. For instance, if the elapsed time is 4 days, it will display "4 days ago".

The above is the detailed content of How to Calculate and Display Time Elapsed Since a Date 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template