计算并显示日期为'secs ago','mins ago','hours ago'等

时间:2010-03-16 03:49:14

标签: php mysql date

我有一个小的自定义博客类型的东西,并希望显示评论旁边发布的日期。

我想以下列格式进行:

发布于23秒前 发布于43分钟前
1小时前发布了 发布于1天前
发布于2周前 ... 可能不会比这长得多,因为没有显示超过一个月的文章。

我可以在MySQL中存储日期时间或时间戳格式的实际日期......

任何人都知道PHP可以使用的功能吗?我还没找到任何适合的东西。

2 个答案:

答案 0 :(得分:5)

您可以使用以下函数并将其称为format_interval(time() - $saved_timestamp),其中$saved_timestamp是您感兴趣的“事件”的时间戳。(以下代码在 GNU General下获得许可公共许可证v2或后续。)

function format_interval($interval, $granularity = 2) {
  $units = array('1 year|@count years' => 31536000, '1 week|@count weeks' => 604800, '1 day|@count days' => 86400, '1 hour|@count hours' => 3600, '1 min|@count min' => 60, '1 sec|@count sec' => 1);
  $output = '';
  foreach ($units as $key => $value) {
    $key = explode('|', $key);
    if ($interval >= $value) {
      $floor = floor($interval / $value);
      $output .= ($output ? ' ' : '') . ($floor == 1 ? $key[0] : str_replace('@count', $floor, $key[1]));
      $interval %= $value;
      $granularity--;
    }

    if ($granularity == 0) {
      break;
    }
  }

  return $output ? $output : '0 sec';
}

$ granularity是要显示的不同单位的数量。例如,format_interval(32745600)将返回"1 year 2 weeks"

我展示的代码是Drupal 7附带的简化版format_interval(),它是在GNU General Public License v2 or successive许可下分发的代码。 (另见COPYRIGHT.txt
我取消了Drupal特有的部分,并留下了使用普通PHP函数的代码。

答案 1 :(得分:2)

据我所知,PHP没有内置函数来完成此任务,但似乎已经为此目的编写了函数。

一个here似乎能够做到你需要它。 (你可能需要调整一下)