PHP如何将时间转换为“xx分钟前”的格式_PHP友好时间格式化函数实现

答案:该PHP函数将时间戳或日期字符串转换为“xx分钟前”等友好格式,通过计算当前时间与目标时间的差值,结合语言配置返回“几秒前”“几分钟前”直至“几天前”的中文提示,提升用户体验。

php如何将时间转换为“xx分钟前”的格式_php友好时间格式化函数实现

在PHP中,将时间转换为“xx分钟前”这种友好格式,核心在于计算目标时间与当前时间的时间差,然后根据这个差值,判断并输出对应的“几秒前”、“几分钟前”、“几小时前”乃至“几天前”的文本。这通常需要一个自定义函数来封装逻辑,处理不同时间单位的转换,以提升用户阅读体验。

解决方案

实现一个PHP函数来将给定的时间戳或日期字符串格式化为“xx分钟前”的友好形式,这其实是一个非常常见的需求,尤其是在社交媒体、评论区等场景。我个人在处理这类需求时,倾向于使用

DateTime
登录后复制

对象,因为它在处理时区和日期解析方面更为健壮,尽管对于简单的Unix时间戳,直接的数学运算也行。

笔魂AI

笔魂AI

笔魂AI绘画-在线AI绘画、AI画图、AI设计工具软件

笔魂AI258


查看详情
笔魂AI

下面是一个我常用的函数实现:

<?php

/**
 * 将时间戳或日期字符串转换为“xx时间前”的友好格式
 *
 * @param int|string|DateTime $time 目标时间,可以是Unix时间戳、日期字符串或DateTime对象
 * @param string $locale 语言环境,默认为中文
 * @return string 格式化后的友好时间字符串
 */
function formatFriendlyTimeAgo($time, $locale = 'zh')
{
    // 确保输入是DateTime对象或可转换为时间戳
    $targetDateTime = null;
    if ($time instanceof DateTime) {
        $targetDateTime = $time;
    } elseif (is_numeric($time)) {
        // 如果是数字,尝试直接创建DateTime对象
        try {
            $targetDateTime = (new DateTime())->setTimestamp($time);
        } catch (Exception $e) {
            // 错误处理,例如返回原始输入或默认值
            return (string)$time;
        }
    } elseif (is_string($time)) {
        // 如果是字符串,尝试解析为DateTime对象
        try {
            $targetDateTime = new DateTime($time);
        } catch (Exception $e) {
            return (string)$time;
        }
    } else {
        return (string)$time; // 无法识别的输入
    }

    $currentTime = new DateTime();
    $diff = $currentTime->getTimestamp() - $targetDateTime->getTimestamp();

    // 未来时间处理,虽然标题是“xx分钟前”,但我们稍微处理一下
    if ($diff < 0) {
        return '刚刚'; // 或者可以显示“未来”
    }

    // 定义不同语言的单位和后缀
    $langConfig = [
        'zh' => [
            'year'   => '年',
            'month'  => '个月',
            'week'   => '周',
            'day'    => '天',
            'hour'   => '小时',
            'minute' => '分钟',
            'second' => '秒',
            'ago'    => '前',
            'just_now' => '刚刚'
        ],
        // 可以添加更多语言,例如英文
        'en' => [
            'year'   => 'year',
            'month'  => 'month',
            'week'   
登录后复制

以上就是PHP如何将时间转换为“xx分钟前”的格式_PHP友好时间格式化函数实现的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1515202.html

发表回复

Your email address will not be published. Required fields are marked *