Yii2GridView date formatting and implementation date searchable case study by White Wolf stack author: White Wolf Source: http://www.manks.top/article/yii2_gridview_dateformat_search
The copyright of this article belongs to the Author. You are welcome to repost this article, but you must keep this statement without the author's consent and provide the original article connection clearly on the article page. Otherwise, you will be entitled to pursue legal liability.
Date formatting. let's take a look.
We will discuss the situation in detail.
1. if the time format of your database field created_at is date or datetime, it is very easy to directly output this field created_at in the gridview, as shown on the right
2. if the timestamp type stored in the database is shown on the left side of the data center, output the data as follows:
[ 'attribute' => 'created_at', 'value' => function ($model) { return date('Y-m-d H:i:s', $model->created_at); },],[ 'attribute' => 'created_at', 'format' => ['date', 'Y-m-d H:i:s'],],
The preceding two formats can be output. However, if you want to implement the search mechanism, if your database is saved in the datetime type, it is very convenient, dataProvider does not need to be modified,
The code is as follows:
$query->andFilterWhere([ // ...... 'created_at' => $this->created_at, // ......]);
If your database is saved with a timestamp,
Step 1: modify the corresponding rule, as shown in
Step 2: modify dataProvider by referring to the following code:
// In the search input box, the input format is generally, instead of the timestamp. // The output of 2016-01-01 is nothing more than the data of the day. Therefore, the code is as follows if ($ this-> created_at) {$ createdAt = strtotime ($ this-> created_at); $ createdAtEnd = $ createdAt + 24*3600; $ query-> andWhere ("created_at >={$ createdAt} AND created_at <={ $ createdAtEnd }");}
Here is a small summary. we recommend that you use the datetime type. in my opinion, it is very troublesome to save the timestamp. if you have good suggestions, leave a message below for us to share.