数秒至数分钟,数天至数周 [英] seconds to minutes and days to weeks

查看:88
本文介绍了数秒至数分钟,数天至数周的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,如何使用PHP才能拥有一个自动化的系统,该系统可以做到这一点: 如果我们有$seconds= 120;并且脚本应获取此值,请确保该值等于2分钟,然后在分钟中打印此值.就像我们希望将其保留几天一样,假设$days = 7;脚本需要获取此值,检查天数,在这种情况下,它需要打印 1周.谢谢你们!

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!

推荐答案

<?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), "\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";

输出:

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)

这篇关于数秒至数分钟,数天至数周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆