Code Snippets

  

PHP Source Code


Welcome to Dream.In.Code
Become a PHP Expert!

Join 149,628 PHP Programmers for FREE! Get instant access to thousands of PHP experts, tutorials, code snippets, and more! There are 2,015 people online right now. Registration is fast and FREE... Join Now!





Years, Days, Hours, Minutes Ago

The time_since() function returns a nicely formatted Days Ago type date. Just pass a UNIX timestamp in and you'll get the string back out.

Submitted By: skyhawk133
Actions:
Rating:
Views: 7,276

Language: PHP

Last Modified: March 2, 2005
Instructions: Call using time_since(aUNIXTimeStamp);

Returns a string.

Snippet


  1. /* Works out the time since the entry post, takes a an argument in unix time (seconds) */
  2. function time_since($original) {
  3.     // array of time period chunks
  4.     $chunks = array(
  5.         array(60 * 60 * 24 * 365 , 'year'),
  6.         array(60 * 60 * 24 * 30 , 'month'),
  7.         array(60 * 60 * 24 * 7, 'week'),
  8.         array(60 * 60 * 24 , 'day'),
  9.         array(60 * 60 , 'hour'),
  10.         array(60 , 'minute'),
  11.     );
  12.    
  13.     $today = time(); /* Current unix time  */
  14.     $since = $today - $original;
  15.    
  16.     // $j saves performing the count function each time around the loop
  17.     for ($i = 0, $j = count($chunks); $i < $j; $i++) {
  18.        
  19.         $seconds = $chunks[$i][0];
  20.         $name = $chunks[$i][1];
  21.        
  22.         // finding the biggest chunk (if the chunk fits, break)
  23.         if (($count = floor($since / $seconds)) != 0) {
  24.             // DEBUG print "<!-- It's $name -->\n";
  25.             break;
  26.         }
  27.     }
  28.    
  29.     $print = ($count == 1) ? '1 '.$name : "$count {$name}s";
  30.    
  31.     if ($i + 1 < $j) {
  32.         // now getting the second item
  33.         $seconds2 = $chunks[$i + 1][0];
  34.         $name2 = $chunks[$i + 1][1];
  35.        
  36.         // add second item if it's greater than 0
  37.         if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
  38.             $print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
  39.         }
  40.     }
  41.     return $print;
  42. }

Copy & Paste


Comments


Glasseater 2008-02-03 18:32:46

oooo... I like :D Thanks for sharing this one.

ludjer 2008-12-02 05:26:47

looks good gona give it a try thanks

RayRayAngel 2008-12-30 04:55:49

What if I want to go the other way? Instead of counting time since.... counting down to the original value?


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.




Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live PHP Help!

PHP Tutorials

Reference Sheets

PHP Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month