Home  >  Article  >  Backend Development  >  Date formatting in GridView in Yii2 and making dates searchable

Date formatting in GridView in Yii2 and making dates searchable

不言
不言Original
2018-06-08 10:22:121939browse

This article mainly introduces Yii2 GridView date formatting and implementation of date searchable tutorial related information, friends in need can refer to it

I 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 your database field created_at is stored in the time format It is date or datetime. It is very simple. Just output the field created_at directly in the gridview, as shown on the right side of the above figure.

2. If the timestamp type stored in the database is as shown on the left side of the above figure. , you need to output it 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 ways to output the format, both are acceptable. However, if you want to implement a search mechanism, it is very convenient if your database stores 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.

First step, modify the corresponding rules as shown in the figure below

Second step, modify the dataProvider, please refer to the following code

//我们搜索输入框中输入的格式一般是 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}");
}

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Implement pathinfo and ThinkPHP’s URL pattern under Nginx

##Yii2.0 implements pathinfo form Access configuration method

The above is the detailed content of Date formatting in GridView in Yii2 and making dates searchable. For more information, please follow other related articles on the PHP Chinese website!

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