0

Possible Duplicate:
PHP: producing relative date/time from timestamps

please see the example of PHP code:

<?php

$now = date("Y-m-d H:i:s");  
$comment_added = date("2012-05-25 22:10:00");  

?>

As the output, I would like to get something like this (depending on when a comment has been added):

Comment has been added 21 minutes ago.
Comment has been added 15 hours ago.
Comment has been added 2 days ago.
Comment has been added 3 months ago.
Comment has been added 4 years ago.

I would like to get a function, where it will be selected automatically. Any examples would be appreciated.

Community
  • 1
  • 1
  • It is such an obvious duplicate that I am not going to even bother flagging it. – Gajus Sep 08 '12 at 14:50
  • 2
    If so, can you paste the url ? Why always people saying "it's duplicate" without pasting correct url? The whole internet will be soon one big duplicate :] –  Sep 08 '12 at 14:51
  • See [Calculating relative time](http://stackoverflow.com/questions/11/calculating-relative-time). It's C# but you should have no trouble converting it to PHP, it's pretty straightforward. – Alexei Sep 08 '12 at 14:53
  • 1
    @Guy: Obvious for you. It doesn't mean it is obvious for everyone. – Jocelyn Sep 08 '12 at 14:55

1 Answers1

1

This should work.

<?php

$now = date("Y-m-d H:i:s");  
$comment_added = date("2012-05-25 22:10:00");

$diff = strtotime($now) - strtotime($comment_added);
if ($diff > (365*24*3600)) {
    $type = 'year';
    $value = floor($diff / (365*24*3600));
} else if ($diff > (30*24*3600)) {
    $type = 'month';
    $value = floor($diff / (30*24*3600));
} else if ($diff > (24*3600)) {
    $type = 'day';
    $value = floor($diff / (24*3600));
} else if ($diff > 3600) {
    $type = 'hour';
    $value = floor($diff / 3600);
} else if ($diff > 60) {
    $type = 'min';
    $value = floor($diff / 60);
} else {
    $type = 'sec';
    $value = $diff;
}

$plurial = '';
if ($value > 1)
{
    $plurial .= 's';
}
echo "Comment added {$value} {$type}{$plurial} ago.";

?>
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153