TimeAgo - 年和月前

时间:2014-03-05 23:44:24

标签: php datetime

我的unixtime是1336608000

正好是2012-5-10。

1年10个月前从今天起 - 2014-03-06

现在我要做的是输出年份和月份。所以我想显示:

1 year 10 months ago.

我在Stackoverflow和整个互联网上看到的最多timeAgo函数显示时间前“2年前”这是错误的。我尝试过8-10个php函数来显示确切的月份数

所以我的问题是,是否有一个PHP时间前的功能,显示确切的年和月计数而不是四舍五入?

谢谢

1 个答案:

答案 0 :(得分:1)

我找到this answer by Glavić并且效果很好。

我为你调整了它......

用法: echo time_elapsed_string('2012-5-10',true);

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v;
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}
相关问题