PHP如何计算相对时间?

时间:2012-03-08 15:08:48

标签: php

  

可能重复:
  PHP: producing relative date/time from timestamps

给定特定的DateTime值,如何显示相对时间,如

  • 35分钟前
  • 2小时前
  • 3天前
  • 1个月前
等等等......?

mysql_query("UPDATE users SET lastlogin = ".time()." WHERE id = ".$userID); 

3 个答案:

答案 0 :(得分:1)

这可能会对你有所帮助

function time_ago_en($time)
    {
        if(!is_numeric($time))
            $time = strtotime($time);

        $periods = array("second", "minute", "hour", "day", "week", "month", "year", "age");
        $lengths = array("60","60","24","7","4.35","12","100");

        $now = time();

        $difference = $now - $time;
        if ($difference <= 10 && $difference >= 0)
            return $tense = 'just now';
        elseif($difference > 0)
            $tense = 'ago';
        elseif($difference < 0)
            $tense = 'later';

        for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
            $difference /= $lengths[$j];
        }

        $difference = round($difference);

        $period =  $periods[$j] . ($difference >1 ? 's' :'');
        return "{$difference} {$period} {$tense} ";
    }

实施例

<?php

echp   time_ago_en(time() - 300);
// 5 minutes ago
?>

答案 1 :(得分:0)

strtotime是一个不错的功能

让我更具体一点

strtotime(-5 days);

strtotime(-1 month);

有一个可选的第二个参数,它是你想要开始的时间的另一个时间戳,给你relative时间。为什么选择downvote?

答案 2 :(得分:0)

<?php
function relativeTime($time = false, $limit = 86400, $format = 'g:i A M jS') {
    if (empty($time) || (!is_string($time) &amp;&amp; !is_numeric($time))) $time = time();
    elseif (is_string($time)) $time = strtotime($time);

    $now = time();
    $relative = '';

    if ($time === $now) $relative = 'now';
    elseif ($time > $now) $relative = 'in the future';
    else {
        $diff = $now - $time;

        if ($diff >= $limit) $relative = date($format, $time);
        elseif ($diff < 60) {
            $relative = 'less than one minute ago';
        } elseif (($minutes = ceil($diff/60)) < 60) {
            $relative = $minutes.' minute'.(((int)$minutes === 1) ? '' : 's').' ago';
        } else {
            $hours = ceil($diff/3600);
            $relative = 'about '.$hours.' hour'.(((int)$hours === 1) ? '' : 's').' ago';
        }
    }

    return $relative;
}
?>

Source