/ Published in: PHP
Get time difference in human readable format
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function timeBetween($start,$end) { } /** * Get time difference in human readable format * $start is start time (unix time), $end is end time (unix time), $units is numeric and defines how many time units to display */ function timeSince($start,$end='',$units=2,$words='long') { // $start and $end should be Unix time() format switch($words) { case 'long': $unitName = array( // Change this array to reflect what should be displayed as unit names and pluralization append 'year' => 'year', 'month' => 'month', 'week' => 'week', 'day' => 'day', 'hour' => 'hour', 'minute' => 'minute', 'second' => 'second', 'plural' => 's' ); break; case 'short': $unitName = array( // Change this array to reflect what should be displayed as unit names and pluralization append 'year' => 'yr', 'month' => 'mo', 'week' => 'wk', 'day' => 'day', 'hour' => 'hr', 'minute' => 'min', 'second' => 'sec', 'plural' => 's' ); break; } // Common time periods as an array of arrays ); $since = $end - $start; // Find the difference of time between now and the past // 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}{$unitName['plural']}"; } } } return $output; } /** * Identical to timeSince except your end time should be greater than your start time */ function timeUntil($end,$start='',$units=2) { return timeSince($start,$end,$units); }