首頁 >後端開發 >php教程 >如何將 PHP 時間戳轉換為人類可讀的「Time Ago」字串?

如何將 PHP 時間戳轉換為人類可讀的「Time Ago」字串?

Barbara Streisand
Barbara Streisand原創
2024-12-23 13:28:05824瀏覽

How to Convert PHP Timestamps to Human-Readable

在PHP 中將時間戳轉換為人類可讀的過去時間

在PHP 中,您可以使用time_elapsed_string() 函數將時間戳轉換為經過的時間字串。

功能定義

function time_elapsed_string($datetime, $full = false) {
    // Get the current date and time
    $now = new DateTime;

    // Create a DateTime object from the input timestamp
    $ago = new DateTime($datetime);

    // Calculate the difference between the current time and the input timestamp
    $diff = $now->diff($ago);

    // Convert weeks and days to days
    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    // Create an array of time units and their corresponding English names
    $string = [
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    ];

    // Iterate through the time units and add them to the output string if they are greater than 0
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    // If the `$full` parameter is false, only return the first time unit
    if (!$full) $string = array_slice($string, 0, 1);

    // Return the formatted time elapsed string
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

用法

echo time_elapsed_string('2013-05-01 00:22:35'); // Output: 4 months ago
echo time_elapsed_string('@1367367755');          // Output: 4 months ago
echo time_elapsed_string('2013-05-01 00:22:35', true); // Output: 4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago

以上是如何將 PHP 時間戳轉換為人類可讀的「Time Ago」字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn