/ Published in: PHP
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function timeFromNow($timestamp,$detailed=false, $max_detail_levels=8, $precision_level='second'){ #If the difference is positive "ago" - negative "away" ($timestamp >= $now) ? $action = 'away' : $action = 'ago'; # Set the periods of time $diff = ($action == 'away' ? $timestamp - $now : $now - $timestamp); # round diff to the precision_level # if the diff is very small, display for ex "just seconds ago" if ($diff <= 10) { $agotxt = $periods[$periodago]; return "just $agotxt $action"; } # Go from decades backwards to seconds $time = ""; if($diff > $lengths[$i-1] && ($max_detail_levels > 0)) { # if the difference is greater than the length we are checking... continue $val = floor($diff / $lengths[$i-1]); # 65 / 60 = 1. That means one minute. 130 / 60 = 2. Two minutes.. etc $time .= $val ."". $periods[$i-1].($val > 1 ? ' ' : ' '); # The value, then the name associated, then add 's' if plural $diff -= ($val * $lengths[$i-1]); # subtract the values we just used from the overall diff so we can find the rest of the information if(!$detailed) { $i = 0; } # if detailed is turn off (default) only show the first set found, else show all information $max_detail_levels--; } } # Basic error checking. if($time == "") { return "Unable to calculate time"; } else { return $time.$action; } }