April 25, 2007
PHP relative time function 0
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 Raleigh, NC. I'm married to an awesome lady and we have an awesome one year old son. If you'd like to find out more about my fascinating life, check this stuff out:
Track me
Visit my sites
Other stuff
Latest posts
- Google ASCII Art Easter Egg
- Is it so crazy that someone would play VATFUL?
- Now that’s a quesadilla
- Automatically playing audio with HTML5 and Javascript (even on the iPad)
- Prevent console.log() errors
- Tumblin’
- omgtru updates and iPhone web app lessons learned
- Really?
- Easy form hints: HTML5 input placeholders
- Anthem Type
Categories
- apple
- art
- audio
- baseball
- bikes
- books
- browsers
- comedy
- complaints
- crime
- death
- dumb things
- energy
- environment
- family
- fonts
- food
- friends
- gadgets
- games
- henry
- html
- internet
- ipad
- iphone
- itunes
- javascript
- jquery
- life
- los angeles
- marriage
- movies
- msgblorb
- music
- mysql
- new york
- omgtru
- os x
- pasadena
- photos
- php
- plugins
- podcasting
- politics
- portland
- pugs
- rss
- ruby
- splideo
- subversion
- ubuntu
- Uncategorized
- video
- watir
- wordpress
- work
No Responses
Please Wait
Leave a Reply