Home >Backend Development >PHP Tutorial >How Can I Efficiently Display Time Elapsed Since a Given Date-Time Stamp in PHP?
Determining Time Elapsed from a Date-Time Stamp in PHP
When dealing with date-time data, it's often essential to calculate the elapsed time since a specific point in the past. This practical question seeks to find an efficient method to convert a date-time stamp like "2010-04-28 17:25:43" into a user-friendly format such as "xx Minutes Ago" or "xx Days Ago."
To tackle this problem effectively, consider the following solution:
$time = strtotime('2010-04-28 17:25:43'); echo 'Event occurred ' . humanTiming($time) . ' ago'; function humanTiming($time) { $time = time() - $time; $time = ($time < 1) ? 1 : $time; $units = [ 31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second', ]; foreach ($units as $unit => $text) { if ($time < $unit) { continue; } $numUnits = floor($time / $unit); return "$numUnits $text" . (($numUnits > 1) ? 's' : ''); } }
This solution utilizes PHP's strtotime() function to convert the input date-time string into a timestamp. It then subtracts the current timestamp from the input timestamp to obtain the elapsed time. To translate the elapsed time into a user-friendly format, it employs a predefined array of unit-to-text mappings ($units) and iterates through them to determine the appropriate unit (e.g., "day," "hour," etc.).
By implementing this approach, you can effectively determine and display the time elapsed since a given date-time stamp in PHP, providing clarity and convenience in your applications.
The above is the detailed content of How Can I Efficiently Display Time Elapsed Since a Given Date-Time Stamp in PHP?. For more information, please follow other related articles on the PHP Chinese website!