seconds to minutes and days to weeks

后端 未结 3 1706
时光说笑
时光说笑 2020-12-19 19:26

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

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 20:03

    = 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), "\n";
        echo formatSeconds(30), "\n";
        echo formatSeconds(300), "\n";
        echo formatSeconds(3000), "\n";
        echo formatSeconds(30000), "\n";
        echo formatSeconds(300000), "\n";
        echo formatSeconds(3000000), "\n";
        echo formatSeconds(30000000), "\n";
    

    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)
    

提交回复
热议问题