---
title: "php处理日期格式为秒前、分前、小时前、昨天、前天"
author: "cindylu520"
date: "2012-02-10T09:26:29Z"
tags: ["PHP"]
categories: ["Web前端"]
slug: "php"
draft: false
lastmod: "2012-02-10T10:39:56Z"
id: 1401508
url: "https://cindylu520.iteye.com/blog/1401508"
---

```
    /**
     * 将日期格式根据以下规律修改为不同显示样式
     * 小于1分钟 则显示多少秒前
     * 小于1小时，显示多少分钟前
     * 一天内，显示多少小时前
     * 3天内，显示前天22:23或昨天:12:23。
     * 超过3天，则显示完整日期。
     * @static
     * @param  $sorce_date 数据源日期 unix时间戳
     * @return void
     */
    public static function getDateStyle($sorce_date){

        self::$nowTime = time();  //获取今天时间戳

//        echo '数据源时间戳：'.$sorce_date . ' = '. date('Y-m-d H:i:s',$sorce_date);
//        echo "\n 当前时间戳:". date('Y-m-d H:i:s',self::$nowTime)."\n";

        $timeHtml = ''; //返回文字格式
        $temp_time = 0;
        switch($sorce_date){

            //一分钟
            case ($sorce_date+60)&gt;=self::$nowTime:
                $temp_time = self::$nowTime-$sorce_date;
                $timeHtml = $temp_time ."秒前";
                break;

            //小时
            case ($sorce_date+3600)&gt;=self::$nowTime:
                $temp_time = date('i',self::$nowTime-$sorce_date);
                $timeHtml = $temp_time ."分钟前";
                break;

            //天
            case ($sorce_date+3600*24)&gt;=self::$nowTime:
                $temp_time = date('H',self::$nowTime)-date('H',$sorce_date);
                $timeHtml = $temp_time .'小时前';
                break;

            //昨天
            case ($sorce_date+3600*24*2)&gt;=self::$nowTime:
                $temp_time = date('H:i',$sorce_date);
                $timeHtml = '昨天'.$temp_time ;
                break;

            //前天
            case ($sorce_date+3600*24*3)&gt;=self::$nowTime:
                $temp_time  = date('H:i',$sorce_date);
                $timeHtml = '前天'.$temp_time ;
                break;

            //3天前
            case ($sorce_date+3600*24*4)&gt;=self::$nowTime:
                $timeHtml = '3天前';
                break;

            default:
                $timeHtml = date('Y-m-d',$sorce_date);
                break;

        }
        return $timeHtml;

    }
```