文章目录
本文最后更新于 2022-10-14,已超过 365 天未更新,内容可能已失效。

第一种代码

<?php
function _times_ago($time) {
    if (is_int($time)) {
        $time = intval($time);
    } else {
        $time = strtotime($time);
    }

 
    $ctime = intval(strtotime(current_time('mysql')));
    $t     = $ctime - $time; //时间差 (秒)

    if ($t < 0) {
        return date('Y-m-d H:i', $time);
    }
    $y = intval(date('Y', $ctime) - date('Y', $time)); //是否跨年
    if (0 == $t) {
        $text = '刚刚';
    } elseif ($t < 60) {
        //一分钟内
        $text = $t . '秒前';
    } elseif ($t < 3600) {
        //一小时内
        $text = floor($t / 60) . '分钟前';
    } elseif ($t < 86400) { //一天内
        $text = floor($t / 3600) . '小时前'; // 一天内
    } elseif ($t < 2592000) {
        //30天内
        if ($time > strtotime(date('Ymd', strtotime("-1 day")))) {
            $text = '昨天';
        } elseif ($time > strtotime(date('Ymd', strtotime("-2 days")))) {
            $text = '前天';
        } else {
            $text = floor($t / 86400) . '天前';
        }
    } elseif ($t < 31536000 && 0 == $y) {
        //一年内 不跨年
        $m = date('m', $ctime) - date('m', $time) - 1;

        if (0 == $m) {
            $text = floor($t / 86400) . '天前';
        } else {
            $text = $m . '个月前';
        }
    } elseif ($t < 31536000 && $y > 0) {
        //一年内 跨年
        $text = (12 - date('m', $time) + date('m', $ctime)) . '个月前';
    } else {
        $text = (date('Y', $ctime) - date('Y', $time)) . '年前';
    }

    return $text;
}

第二种

function _time_ago($time) {
    $time       = strtotime($time);
    $difference = time() - $time;
 
    switch ($difference) {
    case $difference <= '1':
        $msg = '刚刚';
        break;
    case $difference > '1' && $difference <= '60':
        $msg = floor($difference) . '秒前';
        break;
    case $difference > '60' && $difference <= '3600':
        $msg = floor($difference / 60) . '分钟前';
        break;
    case $difference > '3600' && $difference <= '86400':
        $msg = floor($difference / 3600) . '小时前';
        break;
    case $difference > '86400' && $difference <= '2592000':
        $msg = floor($difference / 86400) . '天前';
        break;
    case $difference > '2592000':
        $msg = '' . date('Y-m-d', $time) . '';
        break;
    }
    return $msg;
}

 

CC 许可协议
署名-非商业性使用-相同方式共享 4.0 国际 了解协议
文章链接:https://zptheme.com/5376.html
本文作者:子佩·来源:子佩工作室

除非注明,子佩工作室 文章均为原创,转载请以链接形式标明本文地址。

相关推荐

登录后即可发表评论

社交账号登录

全部评论 (6)