把秒数转成“Y年D天H小时M分S秒”的格式

<?php
/**
 * 把秒数转成“Y年D天H小时M分S秒”的格式
 *
 * @param int $seconds 秒数
 * @return string Y年D天H小时M分S秒
 */
function seconds_format($seconds)
{
    $str = '';

    $value = array('years' => 0, 'days' => 0, 'hours' => 0, 'minutes' => 0, 'seconds' => 0,);

    // 在最科学且无误差的年的概念下,一年应该是365天5小时48分46秒,即31556926秒
    if ($seconds >= 31556926) {
        $value['years'] = floor($seconds / 31556926);
        $str .= "{$value['years']}年";
        if (!$seconds %= 31556926) {
            return $str;
        }
    }

    if ($seconds >= 86400) {
        $value['days'] = floor($seconds / 86400);
        $str .= "{$value['days']}天";
        if (!$seconds %= 86400) {
            return $str;
        }
    }

    if ($seconds >= 3600) {
        $value['hours'] = floor($seconds / 3600);
        $str .= "{$value['hours']}小时";
        if (!$seconds %= 3600) {
            return $str;
        }
    }

    if ($seconds >= 60) {
        $value['minutes'] = floor($seconds / 60);
        $str .= "{$value['minutes']}分";
        if (!$seconds %= 60) {
            return $str;
        }
    }

    $value['seconds'] = floor($seconds);

    $str .= "{$value['seconds']}秒";

    return $str;
}

echo seconds_format(0)         . PHP_EOL; // 0秒
echo seconds_format(1)         . PHP_EOL; // 1秒
echo seconds_format(59)        . PHP_EOL; // 59秒
echo seconds_format(60)        . PHP_EOL; // 1分
echo seconds_format(61)        . PHP_EOL; // 1分1秒
echo seconds_format(300)       . PHP_EOL; // 5分
echo seconds_format(365)       . PHP_EOL; // 6分5秒
echo seconds_format(3599)      . PHP_EOL; // 59分59秒
echo seconds_format(3600)      . PHP_EOL; // 1小时
echo seconds_format(3601)      . PHP_EOL; // 1小时1秒
echo seconds_format(3650)      . PHP_EOL; // 1小时50秒
echo seconds_format(7654)      . PHP_EOL; // 2小时7分34秒
echo seconds_format(9876)      . PHP_EOL; // 2小时44分36秒
echo seconds_format(12345)     . PHP_EOL; // 3小时25分45秒
echo seconds_format(76543)     . PHP_EOL; // 21小时15分43秒
echo seconds_format(86399)     . PHP_EOL; // 23小时59分59秒
echo seconds_format(86400)     . PHP_EOL; // 1天
echo seconds_format(87654)     . PHP_EOL; // 1天20分54秒
echo seconds_format(1234567)   . PHP_EOL; // 14天6小时56分7秒
echo seconds_format(12345678)  . PHP_EOL; // 142天21小时21分18秒
echo seconds_format(31556925)  . PHP_EOL; // 365天5小时48分45秒
echo seconds_format(31556926)  . PHP_EOL; // 1年
echo seconds_format(123456789) . PHP_EOL; // 3年333天4小时6分51秒
echo seconds_format(315569260) . PHP_EOL; // 10年

Copyright © 2024 码农人生. All Rights Reserved