April 25, 2007
PHP relative time function
find more posts in: phpI couldn’t find a PHP function that would take a number of seconds as input and give me something like “3 weeks and 2 days” so I put this together:
function rel_time($seconds){ if($seconds < 60){ if($seconds < 0){ $seconds = 0; } switch($seconds){ case 1: return "1 second"; break; default: return "$seconds seconds"; break; } }else{ $date_push = array(); $time_units = array( 'year' => (365*24*60*60), 'month' => (30*24*60*60), 'week' => (7*24*60*60), 'day' => (24*60*60), 'hour' => (60*60), 'minute' => (60)); foreach($time_units as $unit=>$unit_time){ $total = 0; if($unit=='day' && count($date_push) && ($seconds < $time_units['day'])){ $seconds = 0; } while($seconds >= $unit_time){ $seconds -= $unit_time; $total++; } switch ($total){ case 0: break; case 1: $date_push[] = "1 $unit"; break; default: $date_push[] = "$total {$unit}s"; break; } if(count($date_push) == 2){ break; } } return implode(" and ", $date_push); } }
Example usage:
$rel_time = rel_time(time() - $timestamp); print "Posted $rel_time ago";
It’s not as efficient as it could be, but it gets the job done for now. And it’s pretty easy to configure it for the time units that you want to use.
My name is Joey Nelson. I'm a web developer living in Portland, OR. I'm married to an awesome lady and we have two weird little pugs. I do a weekly comedy podcast and make dumb songs with this guy Ben. I don't post to this blog very often, and very few people actually read it. If you'd like to find out more about my fascinating life, check this stuff out:
Stuff
Visit my sites
Visit my friends
Latest posts
Categories
- art
- audio
- baseball
- bikes
- books
- browsers
- complaints
- crime
- death
- dumb things
- energy
- environment
- family
- friends
- gadgets
- internet
- life
- los angeles
- marriage
- movies
- music
- mysql
- new york
- os x
- pasadena
- photos
- php
- plugins
- podcasting
- politics
- portland
- pugs
- rss
- ruby
- splideo
- subversion
- ubuntu
- video
- watir
- wordpress
- work
No Responses
Please Wait
Leave a Reply