PHP如何计算相对时间?

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

给定一个特定的日期时间值,我如何显示相对时间,如

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

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

    这可能会帮助你

    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
    ?>
    

    strtotime是一个很好的功能

    让我更具体一些

    strtotime(-5 days);
    

    要么

    strtotime(-1 month);
    

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


    <?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;
    }
    ?>
    

    资源

    链接地址: http://www.djcxy.com/p/58965.html

    上一篇: PHP How do I calculate relative time?

    下一篇: Print out Relative Date / Time from SQL / PHP Datestamp