Home > Backend Development > PHP Tutorial > How Can I Calculate and Display the Time Elapsed Since a DateTime Stamp in PHP?

How Can I Calculate and Display the Time Elapsed Since a DateTime Stamp in PHP?

Mary-Kate Olsen
Release: 2024-12-19 07:47:10
Original
407 people have browsed it

How Can I Calculate and Display the Time Elapsed Since a DateTime Stamp in PHP?

Determining Time Elapsed Since a DateTime Stamp in PHP

In PHP, obtaining the time passed since a specific date and time stamp is crucial. This information can be useful in displaying elapsed time in a user-friendly format, such as "xx Minutes Ago" or "xx Days Ago."

Solution:

The provided code exemplifies an effective approach to convert a date and time stamp into a relative time format:

<?php
$timestamp = strtotime('2010-04-28 17:25:43');

function humanTiming($timestamp) {
    $difference = time() - $timestamp;
    $tokens = array(
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

    foreach ($tokens as $unit => $text) {
        if ($difference < $unit) continue;
        $units = floor($difference / $unit);
        return $units . ' ' . $text . (($units > 1) ? 's' : '');
    }
}

echo 'Event occurred ' . humanTiming($timestamp) . ' ago';
?>
Copy after login

Explanation:

  • The strtotime() function converts the provided date and time stamp ('2010-04-28 17:25:43') into a UNIX timestamp.
  • The humanTiming() function calculates the difference between the current time and the timestamp.
  • The function then iterates over an array of time units (year, month, week, etc.) and their corresponding text representations.
  • It checks if the time difference is greater than or equal to the current unit and returns the appropriate text representation.
  • Finally, the returned string is appended to the output, indicating the relative time elapsed since the timestamp.

The above is the detailed content of How Can I Calculate and Display the Time Elapsed Since a DateTime Stamp 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