Frank Nwoko
Frank Nwoko

Reputation: 3934

Display date/time in readable and brief format

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;

Upvotes: 0

Views: 187

Answers (2)

Subdigger
Subdigger

Reputation: 2193

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 

}

Upvotes: 2

holgac
holgac

Reputation: 1539

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"

Upvotes: 1

Related Questions