Display elapsed time in a nice format.
1
2 function time_since($older_date, $newer_date = false) {
3
4 $chunks = array(
5 array(60 * 60 * 24 * 365 , 'year'),
6 array(60 * 60 * 24 * 30 , 'month'),
7 array(60 * 60 * 24 * 7, 'week'),
8 array(60 * 60 * 24 , 'day'),
9 array(60 * 60 , 'hour'),
10 array(60 , 'minute'),
11 );
12
13 $newer_date = ($newer_date == false) ? (time()) : $newer_date;
14
15 // difference in seconds
16 $since = $newer_date - $older_date;
17
18 // we only want to output two chunks of time here, eg:
19 // x years, xx months
20 // x days, xx hours
21 // so there are only two bits of calculation below:
22
23 // step one: the first chunk
24 for ($i = 0, $j = count($chunks); $i < $j; $i++) {
25 $seconds = $chunks[$i][0];
26 $name = $chunks[$i][1];
27
28 // finding the biggest chunk (if the chunk fits, break)
29 if (($count = floor($since / $seconds)) != 0) {
30 break;
31 }
32 }
33
34 $output = ($count == 1) ? '1 '.$name : "$count {$name}s";
35
36 // step two: the second chunk
37 if ($i + 1 < $j) {
38 $seconds2 = $chunks[$i + 1][0];
39 $name2 = $chunks[$i + 1][1];
40
41 if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
42 // add to output var
43 $output .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
44 }
45 }
46
47 return $output;
48 }