[PHP] Print out the age of a date in words

I came across a handy piece of code to print out the “age of a date” in words on ThinkPHP. This code should print out the difference between two dates in words (X Days/Months/Weeks/Years). I have modified the original piece of code to print out the number of years as well.

This is a snippet which prints out the difference in words with respective to the current time.

$date_parsed = date_parse($date);
$date_timestamp = mktime(0,0,0, $date_parsed['month'], $date_parsed['day'], $date_parsed['year']);
$now_timestamp = time();
$timestamp_diff = $now_timestamp - $date_timestamp;

if ($timestamp_diff < (60*60*24*7)) {
   echo floor($timestamp_diff/60/60/24)." Days";
elseif ($timestamp_diff > (60*60*24*7*4)) {
   echo floor($timestamp_diff/60/60/24/7)." Weeks";
else {
   $total_months = $months = floor($timestamp_diff/60/60/24/30);
   if($months >= 12) {
      $months = ($total_months % 12);
      $years  = ($total_months - $months)/12;
      echo $years . " Years ";
   if($months > 0)
      echo $months . " Months";
About these ads

Get every new post delivered to your Inbox.

%d bloggers like this: