作者:白狼 出处:http://www.manks.top/article/yii2_gridview_dateformat_search
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
日期格式化,我们先来看看效果图
这个我们分情况讨论
1、如果你的数据库字段created_at存的时间格式是date或者datetime,那很简单,gridview中直接输出该字段created_at即可,如上图中右侧所示
2、如果数据库存入的时间戳类型,如上图中左侧所示,则需要像下面这样进行输出
[ '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'], ],
以上展示了两种方式进行格式输出,都可以。但是,如果想要实现搜索的机制,如果你的数据库存入的是datetime型,很方便,dataProvider不用做修改,
代码如下
$query->andFilterWhere([ // ...... 'created_at' => $this->created_at, // ...... ]);
如果你的数据库存入的是时间戳,
第一步,修改对应规则如下图所示
第二步,修改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 <p>这里做个小总结,建议使用datetime类型,个人觉得存时间戳甚是麻烦,如果你有好的建议,下方留言我们共同交流。</p><div id="MySignature"></div> <div class="clear"></div>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version

Notepad++7.3.1
Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
