Thinkphp 前端视图输出日期时间戳自动转换为时间格式化年月日

需求:实现文章创建按年,月,日归类,并如图格式显示。

2018 年

  • 11 月 ( 1 篇文章 )
    • 24日: 你走了真好,不然总担心你要走 (130)
  • 05 月 ( 1 篇文章 )
    • 12日: 后来的我们 (90)
  • 03 月 ( 2 篇文章 )
    • 31日: 年少不懂《还珠3》,看懂已是而立年 (44)
    • 12日: 要么孤独,要么庸俗 (60)

 

数据库 字段 article_createtime 格式为 timestamp

 

前端代码

<h3 class="al_year">{$article_res.article_createtime|strtotime|date="Y年",###}</h3>
                        <ul class="al_mon_list">
                            <li><span class="al_mon">{$article_res.article_createtime|strtotime|date="m月",###} <em>、</em></span>
                                <ul class="al_post_list">
                                    <li>{$article_res.article_createtime|strtotime|date="d日",###}:
                                        <a href="https://isujin.com/6643">{$article_res.article_title}</a>
                                        <em>(130)</em>
                                    </li>
                                </ul>
                            </li>
                        </ul>

 解释下:

strtotime()把字符串转化为整数时间

date(format, timestamp)把时间戳格式化为更易读的日期和时间

 

百度上搜索有的答案是:

{$article_res.article_createtime|date="y-m-d",###} ,经测试在timestamp格式下会得到一个异常,但是在int格式正常显示

 

有的习惯把日期用int格式保存,则{$article_res.article_createtime|date="y-m-d",###}正常显示,但{$article_res.article_createtime|strtotime|date="y-m-d",###}会得到1970-01-01.

 

 

需求中仅分别需要显示年,或月,或日,可以通过修改格式内容来获得需要的数据date="y",###    date="m",### date="d",###

date="y年",### :2019年

date="m月",###:11月

date="d日",###: 2日

总结


 

如果数据库是 timestamp 格式:{$article_res.article_createtime|strtotime|date="y-m-d",###}

如果数据库是 int 格式:{$article_res.article_createtime|date="y-m-d",###}

              {$article_res.article_createtime|date="y-m-d",###}     {$article_res.article_createtime|strtotime|date="y-m-d",###}
timestamp    异常:A non well formed numeric value encountered 正确值
int  正确值  错误值:1970-01-01
posted @ 2020-02-26 20:16  独自上路  阅读(2416)  评论(0编辑  收藏  举报