如何在php中计算“time ago”

时间:2012-07-14 06:57:21

标签: php

  

可能重复:
  PHP How to find the time elapsed since a date time?

我如何才能及时发布。只是示例3分钟前或超过24小时前和2天前的2012-07-13 17:55:59。

1 个答案:

答案 0 :(得分:3)

<?php
function get_timeago( $ptime )
{
    $etime = time() - $ptime;

    if( $etime < 1 )
    {
        return 'less than 1 second ago';
    }

    $a = array( 12 * 30 * 24 * 60 * 60  =>  'year',
                30 * 24 * 60 * 60       =>  'month',
                24 * 60 * 60            =>  'day',
                60 * 60             =>  'hour',
                60                  =>  'minute',
                1                   =>  'second'
    );

    foreach( $a as $secs => $str )
    {
        $d = $etime / $secs;

        if( $d >= 1 )
        {
            $r = round( $d );
            return 'about ' . $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';
        }
    }
}
?>


Usage:   

   <?php 


     echo get_timeago( $timestamp );

   ?>

同时尝试strtotime()