PbootCms将日期时间转换成几分钟,几小时前的形式

转载网址:https://www.cms88.com/cms/38.html

效果如下是,发布时间可以显示:

刚刚

1小时前;

昨天 几点几分;

前天 几点几分;

年月日 几点几分;

这样的一个个性化日期效果,具体效果可以看本文上方的标题。

 

1,找到ExtLabelController.php,添加代码

路径:\apps\home\controller\ExtLabelController.php

作用:该文件的作用之一,是添加新的方法,扩展单个标签

修改:大约在35行,在“private function test()”的方法下面添加新的方法。

代码:

//转换日期
    private function transtime(){
        $pattern = '/\{transtime\s?\(([^\}]+)\)\}/';
        if (preg_match($pattern, $this->content, $matches)) {
            $this->content = preg_replace_callback(
                $pattern,
                function($matches){
                    $time = strtotime($matches[1]);
                  	$otime = date("Y-m-d H:i",$time);
                    $rtime = date("m-d H:i",$time);
                    $htime = date("H:i",$time); 
                    $time = time() - $time;
                    if ($time < 60){
                        $str = '刚刚';
                    }
                    elseif ($time < 60 * 60){
                        $min = floor($time/60);
                        $str = $min.'分钟前';
                    }elseif ($time < 60 * 60 * 24){
                        $h = floor($time/(60*60));
                        $str = $h.'小时前 '.$htime;
                    }elseif ($time < 60 * 60 * 24 * 3){
                        $d = floor($time/(60*60*24));
                        if($d==1)
                            $str = '昨天 '.$rtime;
                        else
                            $str = '前天 '.$rtime;
                    }else{
                        $str = $otime;
                    }
                    return $str;
                },
                $this->content);
        }
    }

 

然后在run()方法里面执行该方法

代码:

/* 必备启动函数 */
    public function run($content)
    {
        // 接收数据
        $this->content = $content;
        
        // 执行个人自定义标签函数
        $this->test();
        
    //转换日期
	$this->transtime();
		
        // 返回数据
        return $this->content;
    }

  

 

最后在模板页面里,使用该标签

代码:

//在文章内容里添加
{transtime({content:date})}

//在文章列表里添加
{pboot:list}
    {transtime([list:date])}
{/pboot:list}

  

 

posted @ 2022-01-25 11:19  特平庸青年  阅读(366)  评论(0)    收藏  举报