note 86479 deleted from function.time by aidan

From: Date: Wed, 15 Apr 2009 16:09:47 +0000
Subject: note 86479 deleted from function.time by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153339@lists.php.net to get a copy of this message
Note Submitter: jeff ---- I created a function to output human readable format from a timestamp <?php function readable_time($timestamp, $num_times = 2) { //this returns human readable time when it was uploaded (array in seconds) $times = array(31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second'); $now = time(); /* Incorporates fix by Waylon */ $secs = $now - $timestamp; //Fix so that something is always displayed if ($secs == 0) { $secs = 1; } /* /Waylon */ $count = 0; $time = ''; foreach ($times AS $key => $value) { if ($secs >= $key) { //time found $s = ''; $time .= floor($secs / $key); if ((floor($secs / $key) != 1)) $s = 's'; $time .= ' ' . $value . $s; $count++; $secs = $secs % $key; if ($count > $num_times - 1 || $secs == 0) break; else $time .= ', '; } } return $time; } //the second paramater is the number of rounds to output. if you put in more than the time allows, it will just show as much as it can echo readable_time(time()-(60*60*24*8)-3681, 5) . ' ago<br />'; echo readable_time(time()-(60*60*24*8)-3681) . ' ago'; ?> outputs: 1 week, 1 day, 1 hour, 1 minute, 21 seconds ago 1 week, 1 day ago [EDIT BY danbrown AT php DOT net: Includes a fix by "Waylon" from 21-DEC-08 @ 16:00 EST with the following note: "The readable_time function is great, except it doesn't work with times that happened immediately (i.e. the $timestamp == $now). Here's my fix."]

« previous php.notes (#153339) next »