/ Published in: PHP
Display amount of time distance between two timestamps in the 2 largest possible time frame terms, adding plural when appropriate. If the second parameter for ending time stamp is left blank the current time() is used.
usage: `echo timeSince(1300000006,1300162842); // will echo 1 day, 21 hours` and `echo timeSince(1300162702,1300162842); // will echo 2 minutes, 20 seconds`
The last parameter is the number of time units to display (ie: 2 might display minutes, seconds while 3 will display hours, minutes seconds). This defaults to 2.
usage: `echo timeSince(1300000006,1300162842); // will echo 1 day, 21 hours` and `echo timeSince(1300162702,1300162842); // will echo 2 minutes, 20 seconds`
The last parameter is the number of time units to display (ie: 2 might display minutes, seconds while 3 will display hours, minutes seconds). This defaults to 2.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function timeSince($start,$end='',$units=2) { // $start and $end should be Unix time() format // Common time periods as an array of arrays ); $since = $end - $start; // Find the difference of time between now and the past // $end and $start input could be swapped in order to find the time 'until' ;) // Loop around the periods, starting with the biggest $seconds = $periods[$i][0]; $name = $periods[$i][1]; // Find the biggest whole period break; } } $output = ($count == 1) ? '1 '.$name : "$count {$name}s"; $deducted = ($seconds * $count); if ($units > $z && $i + $z < $j){ // Retrieving the next requested relevant period $seconds = $periods[$i + $z][0]; $name = $periods[$i + $z][1]; // Only show it if it's greater than 0 $deducted = $deducted+($seconds * $count); $output .= ($count == 1) ? ', 1 '.$name : ", {$count} {$name}s"; } } } return $output; }