PHP如何查找自日期时间以来经过的时间?

2022-01-13 00:00:00 time timestamp date php relative-time-span

如何查找自像 2010-04-28 17:25:43 这样的日期时间戳以来经过的时间,最终输出的文本应该像 xx Minutes Ago/xx 天前

How to find the time elapsed since a date time stamp like 2010-04-28 17:25:43, final out put text should be like xx Minutes Ago/xx Days Ago

推荐答案

大多数答案似乎都集中在将日期从字符串转换为时间.您似乎主要考虑将日期转换为5 天前"格式等.对吗?

Most of the answers seem focused around converting the date from a string to time. It seems you're mostly thinking about getting the date into the '5 days ago' format, etc.. right?

这就是我要这样做的方式:

This is how I'd go about doing that:

$time = strtotime('2010-04-28 17:25:43');

echo 'event happened '.humanTiming($time).' ago';

function humanTiming ($time)
{

    $time = time() - $time; // to get the time since that moment
    $time = ($time<1)? 1 : $time;
    $tokens = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
    }

}

我还没有测试过,但它应该可以工作.

I haven't tested that, but it should work.

结果会是这样的

event happened 4 days ago

event happened 1 minute ago

干杯

相关文章