Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem you were having was because if $time was less than 1 then there wasn't any lesser denomination for it.</p> <p>I fixed it with an if statement and also renamed a variable</p> <pre><code>function time_elapsed_string($time) { $time_diff = time() - $time; $tokens = array( 31536000 =&gt; 'year', 2592000 =&gt; 'month', 604800 =&gt; 'week', 86400 =&gt; 'day', 3600 =&gt; 'hour', 60 =&gt; 'minute', 1 =&gt; 'second', ); if ($time_diff &lt; 1) return '0 seconds'; foreach($tokens as $unit =&gt; $text) { if($time_diff &lt; $unit) continue; $numberOfUnits = floor($time_diff / $unit); return $numberOfUnits.' '.$text.(($numberOfUnits&gt;1)?'s':''); } } </code></pre> <p>You can also use the following, verbatim from the PHP docs: Source: <a href="http://php.net/manual/en/function.time.php" rel="nofollow">http://php.net/manual/en/function.time.php</a></p> <p>Two quick approaches to getting the time elapsed in human readable form.</p> <p> <pre><code>function time_elapsed_A($secs){ $bit = array( 'y' =&gt; $secs / 31556926 % 12, 'w' =&gt; $secs / 604800 % 52, 'd' =&gt; $secs / 86400 % 7, 'h' =&gt; $secs / 3600 % 24, 'm' =&gt; $secs / 60 % 60, 's' =&gt; $secs % 60 ); foreach($bit as $k =&gt; $v) if($v &gt; 0)$ret[] = $v . $k; return join(' ', $ret); } function time_elapsed_B($secs){ $bit = array( ' year' =&gt; $secs / 31556926 % 12, ' week' =&gt; $secs / 604800 % 52, ' day' =&gt; $secs / 86400 % 7, ' hour' =&gt; $secs / 3600 % 24, ' minute' =&gt; $secs / 60 % 60, ' second' =&gt; $secs % 60 ); foreach($bit as $k =&gt; $v){ if($v &gt; 1)$ret[] = $v . $k . 's'; if($v == 1)$ret[] = $v . $k; } array_splice($ret, count($ret)-1, 0, 'and'); $ret[] = 'ago.'; return join(' ', $ret); } $nowtime = time(); $oldtime = 1335939007; echo "time_elapsed_A: ".time_elapsed_A($nowtime-$oldtime)."\n"; echo "time_elapsed_B: ".time_elapsed_B($nowtime-$oldtime)."\n"; /** Output: time_elapsed_A: 6d 15h 48m 19s time_elapsed_B: 6 days 15 hours 48 minutes and 19 seconds ago. **/ </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload