将给定时间戳转换为之前时间的 PHP 程序

phpserver side programmingprogramming更新于 2025/8/25 0:22:17

要将给定时间戳转换为之前时间,代码如下 −

示例

<?php
function to_time_ago( $time )
{
   $difference = time() - $time;
   if( $difference < 1 )
   {
      return 'less than only a second ago';
   }
   $time_rule = array (
      12 * 30 * 24 * 60 * 60 => 'year',
      30 * 24 * 60 * 60 => 'month',
      24 * 60 * 60 => 'day',
      60 * 60 => 'hour',
      60 => 'minute',
      1 => 'second'
   );
   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 "The timestamp to time ago conversion is ";
echo to_time_ago( time() - 600);
?>

输出

The timestamp to time ago conversion is 10 minutes ago

定义了一个名为"to_time_ago"的函数,用于检查作为参数传递给函数的时间与时间函数之间的差值。如果差值小于 1,则返回一秒钟前的时间。否则,将年、月、日、时、分、秒的值生成一个数组。使用"foreach"循环遍历先前生成的数组。计算时间差并将其打印在控制台上。


相关文章