【发布时间】:2015-07-29 23:58:03
【问题描述】:
我有一个从时间戳获取时间前的功能,我从互联网的某个地方抓取它并开发和优化它。它功能齐全。这里的问题是它只获取时间之前(来自过去的时间戳),它没有处理未来的时间戳(它返回 0 秒前)。 有人可以帮我将此功能添加到函数中吗?
<?php
function time_ago( $ts, $format ) {
// $format = 'l, F d, Y H:i';
$granularity = 1;
$dif = time() - $ts;
if ( $dif < 0 )
return '0 Seconds ago';
elseif ( $dif < 604800 ) { // 604800 7 days / 864000 10 days
$periods = array(
'Week' => 604800,
'Day' => 86400,
'Hour' => 3600,
'Minute' => 60,
'Second' => 1
);
$output = '';
foreach ( $periods as $key => $value ) {
if ( $dif >= $value ) {
$time = round( $dif / $value );
$dif %= $value;
$output .= ( $output ? ' ' : '' ) . $time . ' ';
$output .= ( ( $time > 1 ) ? $key . 's' : $key );
$granularity --;
}
if ( $granularity == 0 )
break;
} // foreach( $periods as $key => $value )
return ($output ? $output : '0 seconds') . ' ago';
} else
return date( $format, $ts );
}
?>
【问题讨论】:
-
调试它并检查它有什么问题。
-
你为什么不使用carbon.nesbot.com之类的东西?
-
如果您“从 Internet 上获取”,您应该花一点时间了解它的作用并在必要时进行更新。将“抓取”扩展到“在 StackOverflow 上抓取并询问”是懒惰的。
-
如果
$dif是负数,那么它在未来。因此,当$dif为负数时,将该值设为正数并让其余代码执行其常规工作。还添加新变量以根据初始$dif值打印不同的时间后缀,例如“X mins ago”/“X min in future”。这应该有效。