Home > php教程 > PHP源码 > body text

php处理日期格式为秒前、分前、小时前、昨天、前天

PHP中文网
Release: 2016-05-25 17:13:15
Original
1058 people have browsed it


    /**
     * 将日期格式根据以下规律修改为不同显示样式
     * 小于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)>=self::$nowTime:
                $temp_time = self::$nowTime-$sorce_date;
                $timeHtml = $temp_time ."秒前";
                break;

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

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

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

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

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

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

        }
        return $timeHtml;

    }
Copy after login

                   

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template