KNOWLEDGE/知识

分享你我感悟

PHP 个性化时间 获得几分,几小时,几天前,几小时前,几月前

发表时间:2024-04-03 14:01:04

作者:小Q

浏览次数:4886

/**
 * 个性化日期显示
 * @static
 * @access public
 * @param datetime $times 日期 支持时间戳 和 日期
 * @return string 返回大致日期
 */
function date_before($times) {
    if ($times == '' || $times == 0) {
        return false;
    }
    //完整时间戳
    $strtotime = is_numeric($times) ? $times : strtotime($times);
    $times_day = date('Y-m-d', $strtotime);
    $times_day_strtotime = strtotime($times_day);
    //今天
    $nowdate_str = strtotime(date('Y-m-d'));
    //精确的时间间隔(秒)
    $interval = time() - $strtotime;
    //今天的
    //dump($times_day_strtotime);dump($nowdate_str);exit;
    if ($times_day_strtotime == $nowdate_str) {
        //小于一分钟
        if ($interval < 60) {
            //$pct = sprintf("%d秒前", $interval);
            $pct = sprintf("1分钟前", $interval);
        }
        //小于1小时
        elseif ($interval < 3600) {
            $pct = sprintf("%d分钟前", ceil($interval / 60));
        } else {
            $pct = sprintf("%d小时前", floor($interval / 3600));
        }
    }elseif ($times_day_strtotime == strtotime(date('Y-m-d', strtotime('-1 days')))) {
        //昨天的
        $pct = '昨天' . date('H:i', $strtotime);
    }elseif ($times_day_strtotime == strtotime(date('Y-m-d', strtotime('-2 days')))) {
        //前天的
        $pct = '前天' . date('H:i', $strtotime);
    }elseif ($interval < (3600 * 24 * 30)) {
        //一个月以内
        $pct = date('m-d', $strtotime);
    }elseif ($interval < (3600 * 24 * 365)) {
        //一年以内
        $pct = date('m-d', $strtotime);
    }else {
        //一年以上
        $pct = date('y-m-d', $strtotime);
    }
    return $pct;
}