Home  >  Article  >  Backend Development  >  A brief analysis of Yii2 GridView date formatting and date searchable tutorial, yii2gridview_PHP tutorial

A brief analysis of Yii2 GridView date formatting and date searchable tutorial, yii2gridview_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:53:50743browse

A brief analysis of Yii2 GridView date formatting and date searchable tutorial, yii2gridview

will first show you the date formatting renderings. If you are satisfied, please continue reading:

We will discuss this on a case-by-case basis

1. If the time format stored in your database field created_at is date or datetime, it is very simple. Just output the field created_at directly in the gridview, as shown on the right side in the above figure

2. If the timestamp type stored in the database is as shown on the left in the above figure, it needs to be output 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 above shows two methods for format output, both are acceptable. However, if you want to implement a search mechanism, it is very convenient if your database is stored in datetime type. The dataProvider does not need to be modified,

The code is as follows

$query->andFilterWhere([
// ......
'created_at' => $this->created_at,
// ......
]);

If your database stores timestamps.

The first step is to modify the corresponding rules as shown below

In the second step, you can refer to the following code to modify the dataProvider

//我们搜索输入框中输入的格式一般是 2016-01-01 而非时间戳
//输出2016-01-01无非是想搜索这一天的数据,因此代码如下
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. It is recommended to use the datetime type. Personally, I think it is very troublesome to save timestamps. If you have good suggestions, please leave me a message and we can learn and make progress together. I would also like to thank you all for your support of the Bangkejia website!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1122882.htmlTechArticleA brief analysis of Yii2 GridView date formatting and making the date searchable tutorial, yii2gridview first shows you the date formatting effect Picture, if you are satisfied, please continue reading: This we...
Statement:
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