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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM