沃梦达 / 编程问答 / php问题 / 正文

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

PHP How to find the time elapsed since a date time?(PHP如何查找自日期时间以来经过的时间?)

本文介绍了PHP如何查找自日期时间以来经过的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何查找自像 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

干杯

这篇关于PHP如何查找自日期时间以来经过的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHP如何查找自日期时间以来经过的时间?

基础教程推荐