note 89547 modified in function.date by danbrown

From: Date: Fri, 13 Mar 2009 02:38:16 +0000
Subject: note 89547 modified in function.date by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-151816@lists.php.net to get a copy of this message
There is probably a much easier way to do this, but this function works. This will return the approximate time elapsed since the unix_timestamp fed to it, in this format: 1 minute ago x:xx (xx minutes ago) x:xx (x hours ago) x/x/x (x hours ago) [ if not the same date] x/x/x (x days ago) x/x/x (x years ago) The function: function getLastUpdate($date){ $time = time(); $d = $time - $date; if($d < 60){ return "1 minute ago"; } if($d < 3600){ $result = floor($d/60); $plural = ($result > 1) ? "s" : ""; return date('g:i a',$date)." <span class=\"soft\">($result minute$plural ago)</span>"; } if($d < 86400){ $result = floor($d/(60*60)); $plural = ($result > 1) ? "s" : ""; $text = (date('n/j/y',$date) != date('n/j/y',$time)) ? date('n/j/y',$date) : date('g:i a',$date); return "$text <span class=\"soft\">($result hour$plural ago)</span>"; } if($d < 2592000){ $result = floor($d/(60*60*24)); $plural = ($result > 1) ? "s" : ""; return date('n/j/y',$date)." <span class=\"soft\">($result day$plural ago)</span>"; } if($d < 311004000){ $result = floor($d/(60*60*24*30)); $plural = ($result > 1) ? "s" : ""; return date('n/j/y',$date)." <span class=\"soft\">($result month$plural ago)</span>"; } $result = floor($d/(60*60*24*30*12)); $plural = ($result > 1) ? "s" : ""; return date('n/j/y',$date)." <span class=\"soft\">($result year$plural ago)</span>"; } --was-- Correction to my function below for calculating the time elapsed since a unix timestamp fed to the function. The original function would have failed at months. Here is the function fixed: function getLastUpdate($date){ $time = time(); $d = $time - $date; if($d < 60){ return "1 minute ago"; } if($d < 3600){ $result = floor($d/60); $plural = ($result > 1) ? "s" : ""; return date('g:i a',$date)." <span class=\"soft\">($result minute$plural ago)</span>"; } if($d < 86400){ $result = floor($d/(60*60)); $plural = ($result > 1) ? "s" : ""; $text = (date('n/j/y',$date) != date('n/j/y',$time)) ? date('n/j/y',$date) : date('g:i a',$date); return "$text <span class=\"soft\">($result hour$plural ago)</span>"; } if($d < 2592000){ $result = floor($d/(60*60*24)); $plural = ($result > 1) ? "s" : ""; return date('n/j/y',$date)." <span class=\"soft\">($result day$plural ago)</span>"; } if($d < 311004000){ $result = floor($d/(60*60*24*30)); $plural = ($result > 1) ? "s" : ""; return date('n/j/y',$date)." <span class=\"soft\">($result month$plural ago)</span>"; } $result = floor($d/(60*60*24*30*12)); $plural = ($result > 1) ? "s" : ""; return date('n/j/y',$date)." <span class=\"soft\">($result year$plural ago)</span>"; } http://php.net/manual/en/function.date.php

« previous php.notes (#151816) next »