Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

php - seconds to minutes and days to weeks

My question is, how with PHP we can have an automated system, which can do this: If we have $seconds= 120; And the script should get this value, see that this is equal to 2 min and then print this value in minutes. Same as we want to have it for days, lets say $days = 7; script needs to get this value, check the number of days and in this case it needs to print 1 week. Thank you guys!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<?php

    /**
     * @param int $secs
     *
     * @return string
     */
    function formatSeconds($secs) {
        $secs = (int)$secs;
        if ( $secs === 0 ) {
            return '0 secs';
        }
        // variables for holding values
        $mins  = 0;
        $hours = 0;
        $days  = 0;
        $weeks = 0;
        // calculations
        if ( $secs >= 60 ) {
            $mins = (int)($secs / 60);
            $secs = $secs % 60;
        }
        if ( $mins >= 60 ) {
            $hours = (int)($mins / 60);
            $mins = $mins % 60;
        }
        if ( $hours >= 24 ) {
            $days = (int)($hours / 24);
            $hours = $hours % 60;
        }
        if ( $days >= 7 ) {
            $weeks = (int)($days / 7);
            $days = $days % 7;
        }
        // format result
        $result = '';
        if ( $weeks ) {
            $result .= "{$weeks} week(s) ";
        }
        if ( $days ) {
            $result .= "{$days} day(s) ";
        }
        if ( $hours ) {
            $result .= "{$hours} hour(s) ";
        }
        if ( $mins ) {
            $result .= "{$mins} min(s) ";
        }
        if ( $secs ) {
            $result .= "{$secs} sec(s) ";
        }
        $result = rtrim($result);
        return $result;
    }

    echo formatSeconds(0), "
";
    echo formatSeconds(30), "
";
    echo formatSeconds(300), "
";
    echo formatSeconds(3000), "
";
    echo formatSeconds(30000), "
";
    echo formatSeconds(300000), "
";
    echo formatSeconds(3000000), "
";
    echo formatSeconds(30000000), "
";

Output:

0 secs
30 sec(s)
5 min(s)
50 min(s)
8 hour(s) 20 min(s)
3 day(s) 23 hour(s) 20 min(s)
4 week(s) 6 day(s) 53 hour(s) 20 min(s)
49 week(s) 4 day(s) 53 hour(s) 20 min(s)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...