Home > Backend Development > PHP Problem > How to convert components in seconds in php

How to convert components in seconds in php

藏色散人
Release: 2023-03-14 22:32:01
Original
2718 people have browsed it

php method to convert components in seconds: 1. Create a PHP sample file; 2. Create "class Calendar{...}"; 3. Use the "function formatSecond(){...}" method Just implement the conversion.

How to convert components in seconds in php

The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer

How to convert ingredients in php seconds?

php automatically converts seconds into components, hours, days, weeks, months, years...

<?php
class Calendar
{
    /**
     * 一分钟的秒数
     */
    const TIME_MINUTE = 60;
    /**
     * 一小时的秒数
     */
    const TIME_HOURS = 3600;
    /**
     * 一天的秒数
     */
    const TIME_DAY = 3600 * 24;
    /**
     * 一周的秒数
     */
    const TIME_WEEK = 3600 * 24 * 7;
    /**
     * 一月的秒数
     */
    const TIME_MONTH = 3600 * 24 * 30;
    /**
     * 一年(平年)的秒数
     */
    const TIME_YEAR = 3600 * 24 * 365;
    /**
     * 一年(闰年年)的秒数
     */
    const TIME_YEAR_INTERCALARY = 3600 * 24 * 366;
    /**
     * 时间=》对应名称
     */
    const TIME_NAMES = [
        0 => &#39;秒&#39;,
        self::TIME_MINUTE => &#39;分钟&#39;,
        self::TIME_HOURS => &#39;小时&#39;,
        self::TIME_DAY => &#39;天&#39;,
        self::TIME_WEEK => &#39;周&#39;,
        self::TIME_MONTH => &#39;月&#39;,
        self::TIME_YEAR => &#39;年&#39;,
    ];
    /**
     * 格式化秒自动到 分或者时 或者 天 等....
     * @param int $second
     * @param string[] $unitString 可以自己定义
     * @return string
     */
    public static function formatSecond($second = 0, $unitString = self::TIME_NAMES)
    {
        ksort($unitString);
        if ($second < self::TIME_MINUTE) return $second . $unitString[0];
        krsort($unitString);
        foreach ($unitString as $time => $unitName) {
            if ($time <= 0) continue;
            $result = floor($second / $time);
            if ($result >= 1) return $result . $unitName;
        }
        return null;
    }
 
}
Copy after login

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to convert components in seconds in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template