PHP 显示相对时间(如"5分钟前")的实现方法

|| 技术教程 | 2025-04-11

在PHP中显示相对时间(如"5分钟前"、"2小时前"等)是Web开发中常见的需求,以下是几种实现方式:

1. 使用PHP内置函数实现

function time_ago($timestamp) {
    $current_time = time();
    $time_diff = $current_time - $timestamp;
    
    $seconds = $time_diff;
    $minutes = round($seconds / 60);       // 60秒=1分钟
    $hours   = round($seconds / 3600);     // 3600秒=1小时
    $days    = round($seconds / 86400);    // 86400秒=1天
    $weeks   = round($seconds / 604800);   // 604800秒=1周
    $months  = round($seconds / 2629440);  // 2629440秒≈1个月(30.44天)
    $years   = round($seconds / 31553280);  // 31553280秒≈1年(365.24天)
    
    if ($seconds <= 60) {
        return "刚刚";
    } elseif ($minutes <= 60) {
        return $minutes == 1 ? "1分钟前" : $minutes . "分钟前";
    } elseif ($hours <= 24) {
        return $hours == 1 ? "1小时前" : $hours . "小时前";
    } elseif ($days <= 7) {
        return $days == 1 ? "昨天" : $days . "天前";
    } elseif ($weeks <= 4.3) {  // 4.3周≈1个月
        return $weeks == 1 ? "1周前" : $weeks . "周前";
    } elseif ($months <= 12) {
        return $months == 1 ? "1个月前" : $months . "个月前";
    } else {
        return $years == 1 ? "1年前" : $years . "年前";
    }
}

// 使用示例
$post_time = strtotime('2023-05-15 14:30:00'); // 假设这是文章发布时间
echo time_ago($post_time); // 输出类似 "5分钟前"

2. 使用DateTime类(PHP 5.3+推荐)

function time_ago($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);
    
    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;
    
    $string = array(
        'y' => '年',
        'm' => '个月',
        'w' => '周',
        'd' => '天',
        'h' => '小时',
        'i' => '分钟',
        's' => '秒',
    );
    
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . $v;
        } else {
            unset($string[$k]);
        }
    }
    
    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . '前' : '刚刚';
}

// 使用示例
echo time_ago('2023-05-15 14:30:00'); // 输出 "5分钟前"

3. 使用Carbon库(Laravel等框架常用)

如果你使用Composer,可以安装Carbon库:

composer require nesbot/carbon

然后使用:

use Carbon\Carbon;

// 简单用法
echo Carbon::parse('2023-05-15 14:30:00')->diffForHumans(); 
// 输出 "5 minutes ago"(英文)或配置中文后显示"5分钟前"

// 配置中文
Carbon::setLocale('zh');
echo Carbon::parse('2023-05-15 14:30:00')->diffForHumans();
// 输出 "5分钟前"

4. 前端实现方案(PHP只提供原始时间)

如果你希望减少服务器负载,可以在前端使用JavaScript实现:

// PHP部分(只输出原始时间)
echo '<span class="time-ago" data-timestamp="'.strtotime($row['created_at']).'"></span>';

// JavaScript部分(使用jQuery)
$(document).ready(function() {
    $('.time-ago').each(function() {
        var timestamp = $(this).data('timestamp');
        $(this).text(moment.unix(timestamp).fromNow());
    });
});

需要引入moment.js库:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/locale/zh-cn.js"></script>

注意事项

  1. 时区问题:确保PHP和数据库使用相同的时区设置
    date_default_timezone_set('Asia/Shanghai');
  2. 性能考虑:频繁计算相对时间可能影响性能,可以考虑:
    • 在数据库查询时计算
    • 使用缓存
    • 采用前端计算方案
  3. 对于未来时间:上述示例需要额外处理未来时间的情况

选择哪种方案取决于你的项目需求和技术栈,简单项目可以用原生PHP实现,复杂项目推荐使用Carbon库。

想了解更多精彩内容,请关注艾特安卓网!