要将给定的时间戳转换为时间,代码如下:
示例
<?php
function to_time_ago( $time )
{
$difference = time() - $time;
if( $difference < 1 )
{
return 1秒钟前;
}
$time_rule = array (
12 * 30 * 24 * 60 * 60 => 年,
30 * 24 * 60 * 60 => 月,
24 * 60 * 60 => 天,
60 * 60 => 小时,
60 => 分钟,
1 => 秒
);
foreach( $time_rule as $sec => $my_str )
{
$res = $difference / $sec;
if( $res >= 1 )
{
$t = round( $res );
return $t . . $my_str .
( $t > 1 ? s : ) . ago;
}
}
}
echo "时间戳到时间之前的转换为";
echo to_time_ago( time() - 600);
?>
输出结果
时间戳到时间之前的转换为 10 分钟前
定义了一个名为“to_time_ago”的函数,该函数检查作为参数传递给该函数的时间与该时间函数之间的差。如果发现该差小于1,则返回1秒前。否则,将在数组中生成年,月,日,时,分和秒。“foreach”循环用于迭代先前生成的数组。将计算时间差并输出显示。