分享一段PHP格式化時間戳的程式碼,可以把時間戳轉化成幾天前,幾個月前的格式

煮茶發表於2019-02-16

格式化時間戳

tags: PHP

CMS中一般顯示時間比較新的文章需要顯示幾分鐘前,幾天前這樣,但是一般資料庫裡面記錄的都是時間戳(至少我習慣這樣),所以就需要一個轉化的過程,根據網上的資料加上自己的修改整理封裝了兩段程式碼

下面是封裝好的方法

function formatTime($time) {
        $time = (int) substr($time, 0, 10);
        $int = time() - $time;
        $str = ``;
        if ($int <= 2){
            $str = sprintf(`剛剛`, $int);
        }elseif ($int < 60){
            $str = sprintf(`%d秒前`, $int);
        }elseif ($int < 3600){
            $str = sprintf(`%d分鐘前`, floor($int / 60));
        }elseif ($int < 86400){
            $str = sprintf(`%d小時前`, floor($int / 3600));
        }elseif ($int < 2592000){
            $str = sprintf(`%d天前`, floor($int / 86400));
        }else{
            $str = date(`Y-m-d H:i:s`, $time);
        }
        return $str;
    }

或者 更詳細的

    public static function formatTime($time)
    {
        if (is_int($time)) {
            $time = intval($time);
        } elseif ($time instanceof Carbon) {
            $time = intval(strtotime($time));
        } else {
            return ``;
        }
        $ctime = time();
        $t = $ctime - $time; //時間差 (秒)

        if ($t < 0) {
            return date(`Y-m-d`, $time);
        }

        $y = intval(date(`Y`, $ctime) - date(`Y`, $time));//是否跨年


        if ($t == 0) {
            $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 && $y == 0) {//一年內 不跨年
            $m = date(`m`, $ctime) - date(`m`, $time) - 1;

            if ($m == 0) {
                $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;
    }

相關文章