Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 42f203f

Browse files
author
uuk020
committed
Human readable duration format 转换时间格式format_duration
1 parent aae4038 commit 42f203f

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

‎format_duration/format_duration.php

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<?php
2+
/**
3+
* Human readable duration format 转换时间格式
4+
* Your task in order to complete this Kata is to write a function which formats a duration, given as a number of seconds, in a human-friendly way.
5+
* The function must accept a non-negative integer. If it is zero, it just returns "now". Otherwise,
6+
* the duration is expressed as a combination of years, days, hours, minutes and seconds.
7+
* formatDuration(62) // returns "1 minute and 2 seconds"
8+
* formatDuration(3662) // returns "1 hour, 1 minute and 2 seconds"
9+
*/
10+
function format_duration($seconds)
11+
{
12+
//排除0的情况
13+
if ($seconds == 0) return 'now';
14+
// 时间计算数组
15+
$date = [
16+
'year' => 60 * 60 * 24 * 365,
17+
'day' => 60 * 60 * 24,
18+
'hour' => 60 * 60,
19+
'minute' => 60,
20+
'second' => 1
21+
];
22+
$arr = [];
23+
// 循环时间数组
24+
foreach ($date as $k => $v) {
25+
// 计算时间
26+
$time = floor($seconds / $v);
27+
// 若$time不等于0 则键加入s
28+
if ($time != 0) {
29+
if ($time > 1) {
30+
$k = $k . 's';
31+
}
32+
// $arr 数组新增计算出的字符串元素
33+
$arr[] = $time . '' . $k;
34+
}
35+
// 减去计算好时间, 循环再算其他分钟秒
36+
$seconds = $seconds - $v * $time;
37+
}
38+
// 若时间格式数组大于1
39+
if (count($arr) > 1) {
40+
// 选取最后一个元素
41+
$last = array_slice($arr, -1, 1);
42+
unset($arr[count($arr) - 1]);
43+
// 拼接字符串
44+
$secondTime = ' and ' . $last[0];
45+
// 数组转换为字符串
46+
return implode(', ', $arr) . $secondTime;
47+
}
48+
return implode(', ', $arr);
49+
50+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /