-
Notifications
You must be signed in to change notification settings - Fork 9
/
Duration.php
executable file
·116 lines (100 loc) · 2.89 KB
/
Duration.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?php
/**
* A class for making time periods readable.
*
* This class allows for the conversion of an integer
* number of seconds into a readable string.
* For example, '121' into '2 minutes, 1 second'.
*
* If an array is passed to the class, the associative
* keys are used for the names of the time segments.
* For example, array('seconds' => 12, 'minutes' => 1)
* into '1 minute, 12 seconds'.
*
* This class is plural aware. Time segments with values
* other than 1 will have an 's' appended.
* For example, '1 second' not '1 seconds'.
*
* @author Aidan Lister <[email protected]>
* @version 1.2.1
* @link http://aidanlister.com/repos/v/Duration.php
*/
class Duration
{
/**
* All in one method
*
* @param int|array $duration Array of time segments or a number of seconds
* @return string
*/
function toString ($duration, $periods = null)
{
if($duration < 60) return "0m";
if (!is_array($duration)) {
$duration = Duration::int2array($duration, $periods);
}
return Duration::array2string($duration);
}
/**
* Return an array of date segments.
*
* @param int $seconds Number of seconds to be parsed
* @return mixed An array containing named segments
*/
function int2array ($seconds, $periods = null)
{
// Define time periods
if (!is_array($periods)) {
$periods = array (
# 'years' => 31556926,
# 'months' => 2629743,
# 'ws' => 604800,
'd' => 86400,
'h' => 3600,
'm' => 60,
#'s' => 1
);
}
// Loop
$seconds = (float) $seconds;
foreach ($periods as $period => $value) {
$count = floor($seconds / $value);
if ($count == 0) {
continue;
}
$values[$period] = $count;
$seconds = $seconds % $value;
}
// Return
if (empty($values)) {
$values = null;
}
return $values;
}
/**
* Return a string of time periods.
*
* @package Duration
* @param mixed $duration An array of named segments
* @return string
*/
function array2string ($duration)
{
if (!is_array($duration)) {
return false;
}
foreach ($duration as $key => $value) {
//$segment_name = substr($key, 0, -1);
//$segment = $value . ' ' . $segment_name;
$segment = "$value$key";
// Plural
//if ($value != 1) {
// $segment .= 's';
//}
$array[] = $segment;
}
$str = implode(', ', $array);
return $str;
}
}
?>