0

I stored my dates and times in unix timestamp format (d1=1387721302, d2=1311343703) and would like to view date differences(past, present and future) in say.

2 Weeks ago

15 Days ago

2 Minutes ago

3 Months ago

1 Year ago

9 Months From Now

4 Days From Now

etc.

..hope you catch the drift? instead of "0 Years, 4 Months, 4 Days" Would appreciate a function or some sort. This is actually what I use now

$date1 = "2007-03-24";
$date2 = "2009-06-26";

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days\n", $years, $months, $days);

Thank you

This is what I tried doing but not accurate but as a guide. Anybody pls help.

if ($years >= 1)
{
    $dis_date = printf("%d years\n", $years);

}elseif ($years <= 0 && $months >= 0)
{
    $dis_date = printf("%d months, %d days\n", $months, $days);

}elseif ($years <=0 && $months <= 0 && $days >= 0)
{
    $dis_date = printf("%d days\n", $days);
}else{
    $dis_date = printf("%d years, %d months, %d days\n", $years, $months, $days);
}


echo $dis_date;
Frank Nwoko
  • 3,816
  • 5
  • 24
  • 33
  • 1
    You can't accurately convert a simple duration in seconds into months or years, as there is no clear mapping between the two. The length of a month and the length of a year can vary. You could work out the actual days, months and years between two dates, but not by starting with a dimple duration. – Mike Jul 22 '11 at 15:49
  • 1
    It looks like you can find answers for both approaches here: [How to calculate the difference between two dates using PHP?](http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – Mike Jul 22 '11 at 15:56

2 Answers2

2
function f1 ($time)
{
  $rel = time() - $time;
  if ($rel < 60 * 60)
    $rel .= ' min ago';
  elseif ($rel < 60 * 60 * 24)
    $rel .= ' hours ago';
  elseif ($rel < 60 * 60 * 24 * 30)
    $rel .= ' days ago';
....
  return $rel 

}
Subdigger
  • 2,166
  • 3
  • 20
  • 42
1

You have years, months and days. You need nothing else. Just check if years is 0, then month is 0, then days is 0. Then print the data accordingly.

Having that kind of control is good actually, you may want to write "60 years" instead of "60 years 2 months 3 days"

holgac
  • 1,509
  • 1
  • 13
  • 25