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.
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 => '秒', self::TIME_MINUTE => '分钟', self::TIME_HOURS => '小时', self::TIME_DAY => '天', self::TIME_WEEK => '周', self::TIME_MONTH => '月', self::TIME_YEAR => '年', ]; /** * 格式化秒自动到 分或者时 或者 天 等.... * @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; } }
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!