最新消息:文章中包含代码时,请遵守代码高亮规范!

关于将秒数转为年日时分秒的函数【原创】

PHP 吕, 行 351浏览 0评论

最近在开发项目中需要用到将秒数转换成时分秒的问题,于是自己写了一个函数,可以选择精度和自定义单位,但是目前还不支持月份的转换。

public function secondsToTime($seconds_cache, $accuracy = ‘s’, $language = ‘chinese’)
{
$language_array[‘chinese’] = [‘年’, ‘个月’, ‘天’, ‘小时’, ‘分钟’, ‘秒’];
$language_array[‘english’] = [‘years’, ‘months’, ‘days’, ‘hours’, ‘minutes’, ‘seconds’];

if (!isset($language_array[$language])) {
return false;
}
if (!is_numeric($seconds_cache)) {
return false;
}

switch ($accuracy) {
case ‘s’:
$seconds = $seconds_cache % 60;
case ‘i’:
$minutes_cache = $seconds_cache % 3600;
if ($minutes_cache > 60) {
$minutes = floor($minutes_cache / 60);
}
case ‘h’:
$hours_cache = $seconds_cache % 86400;
if ($hours_cache > 3600) {
$hours = floor($hours_cache / 3600);
}
case ‘d’:
$days_cache = $seconds_cache % 31556926;
if ($days_cache > 86400) {
$days = floor($days_cache / 86400);
}
case ‘m’:

case ‘y’:
if ($seconds_cache > 31556926) {
$years = floor($seconds_cache / 31556926);
}
break;
default:
$seconds = $seconds_cache;
break;
}

$time = ”;
if (isset($years)) {
$time .= $years . $language_array[$language][0];
}

if (isset($months)) {
$time .= $months . $language_array[$language][1];
}

if (isset($days)) {
$time .= $days . $language_array[$language][2];
}

if (isset($hours)) {
$time .= $hours . $language_array[$language][3];
}

if (isset($minutes)) {
$time .= $minutes . $language_array[$language][4];
}

if (isset($seconds)) {
$time .= $seconds . $language_array[$language][5];
}

if (empty($time)) {
switch ($accuracy) {
case ‘s’:
$time = ‘0’ . $language_array[$language][5];
break;
case ‘i’:
$time = ‘0’ . $language_array[$language][4];
break;
case ‘h’:
$time = ‘0’ . $language_array[$language][3];
break;
case ‘d’:
$time = ‘0’ . $language_array[$language][2];
break;
case ‘m’:
$time = ‘0’ . $language_array[$language][1];
break;
case ‘y’:
$time = ‘0’ . $language_array[$language][0];
break;
default:
$time = ‘0’ . $language_array[$language][5];
break;
}
}

return $time;
}

转载时请注明出处及相应链接,本文永久地址:https://blog.yayuanzi.com/24103.html


pay_weixin
pay_weixin
微信打赏
pay_weixin
支付宝打赏
感谢您对作者leon1的打赏,我们会更加努力!    如果您想成为作者,请点我

您必须 登录 才能发表评论!