PHP Show time Since a given date/time

///PHP Show time Since a given date/time

PHP Show time Since a given date/time

Just a simple function to determine based on a UNIX timestamp how long ago something was done and display it in a readable format. Example of this is I am posting this even though I don’t know how long I’ve been actually using this;\r\n

\r\nFor those of you who are using something like MySQL DATE/DATETIME formats you can easily get the UNIX version of the timestamp by quickly converting it all you need is PHP strtotime(). \r\n\r\nExample:\r\n
\r\n$mysqltimestamp = "2011-05-23 19:27:00"; //get this from your query\r\n$timestamp = strtotime($mysqltimestamp);\r\necho time_since($timestamp);\r\n
\r\n\r\nAll though a much quicker version of that is:\r\n
\r\necho time_since(strtotime($mysqltimestamp));\r\n
\r\n\r\nCode:\r\n
function time_since($original) {\r\n		 // array of time period chunks\r\n		 $chunks = array(\r\n			  array(60 * 60 * 24 * 365 , 'year'),\r\n			  array(60 * 60 * 24 * 30 , 'month'),\r\n			  array(60 * 60 * 24 * 7, 'week'),\r\n			  array(60 * 60 * 24 , 'day'),\r\n			  array(60 * 60 , 'hour'),\r\n			  array(60 , 'minute'),\r\n		 );\r\n\r\n		 $today = time(); /* Current unix time  */\r\n		 $since = $today - $original;\r\n\r\n		 // $j saves performing the count function each time around the loop\r\n		 for ($i = 0, $j = count($chunks); $i < $j; $i++) {\r\n\r\n			  $seconds = $chunks[$i][0];\r\n			  $name = $chunks[$i][1];\r\n\r\n			  // finding the biggest chunk (if the chunk fits, break)\r\n			  if (($count = floor($since / $seconds)) != 0) {\r\n					// DEBUG print "\n";\r\n					break;\r\n			  }\r\n		 }\r\n\r\n		 $print = ($count == 1) ? '1 '.$name : "$count {$name}s";\r\n\r\n		 if ($i + 1 < $j) {\r\n			  // now getting the second item\r\n			  $seconds2 = $chunks[$i + 1][0];\r\n			  $name2 = $chunks[$i + 1][1];\r\n\r\n			  // add second item if it's greater than 0\r\n			  if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {\r\n					$print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";\r\n			  }\r\n		 }\r\n		 return $print;\r\n	}\r\n    echo time_since(1306193250);
By | 2016-10-27T00:23:53+00:00 March 8th, 2012|Code, PHP|0 Comments

About the Author:

Not much to know about me, I'm a 35+ year old coder, geek, gamer..

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: