PHP日期strtotime-各种输出


PHP date strtotime - various output

可能重复:
PHP:从时间戳生成相对日期/时间

请参阅PHP代码示例:

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

作为输出,我想得到这样的东西(取决于何时添加了注释):

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.

我想要一个函数,它将被自动选择。任何例子都将不胜感激。

这应该可以工作。

<?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.";
?>