将YYYY-MM-DD HH-MM-SS转换为......月/日/分钟/小时/秒前

时间:2015-01-21 18:36:20

标签: php date

此问题基于另一个有权获得的StackOverFlow question 在PHP中将时间戳转换为时间,例如1天前,2天前......

勾选的answer无法解释但显示此功能:

function time_elapsed_string($ptime)
{
    $etime = time() - $ptime;

    if ($etime < 1)
    {
        return '0 seconds';
    }

    $a = array( 365 * 24 * 60 * 60  =>  'year',
                 30 * 24 * 60 * 60  =>  'month',
                      24 * 60 * 60  =>  'day',
                           60 * 60  =>  'hour',
                                60  =>  'minute',
                                 1  =>  'second'
                );
    $a_plural = array( 'year'   => 'years',
                       'month'  => 'months',
                       'day'    => 'days',
                       'hour'   => 'hours',
                       'minute' => 'minutes',
                       'second' => 'seconds'
                );

    foreach ($a as $secs => $str)
    {
        $d = $etime / $secs;
        if ($d >= 1)
        {
            $r = round($d);
            return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
        }
    }
}

我的时间格式为 YYYY-MM-DD HH-MM-SS ,例如: 2015-01-21 19:23:09

我的尝试:

echo $target_time = time_elapsed_string(strtotime("2015-01-21 19:23:09"));

它给出了:

45年前。

任何时候也给45岁。我不知道这个功能是如何工作的,但是感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

这可以使用PHP的DateTimeDateDiff对象轻松完成

$datetime1 = new DateTime();
$datetime2 = new DateTime("2015-01-21 19:23:09");
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

有关要传递的格式字符串的完整说明,请查看documentation

答案 1 :(得分:0)

我从http://timeago.yarp.com找到了一个简单有效的解决方案:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://timeago.yarp.com/jquery.timeago.js"></script>
<script>
jQuery(document).ready(function() {
  jQuery("abbr.timeago").timeago();
});
</script>

<abbr class="timeago" title="2015-01-21T21:30:00"></abbr>