Yii2.0 时间格式化显示+搜索总结

数据库保存创建时间 created_at 个人喜欢用 date 或者 datetime 的类型,

但是很多时候时间的保存很多人都是用的 时间戳 的形式,

为此在 显示和搜索 的时候要 加工 一下.

一.格式化显示+单个时间的搜索

显示:

1.若created_at保存的类型是date/datetime 在视图中直接输出即可.

2.若created_at类型是时间戳,则

两种视图格式化显示的方法

// 第一种
[
    "attribute" => "created_at",
    "value" => function ($model) {
        return date("Y-m-d H:i:s", $model->created_at);
    },
],
// 第二种(个人推荐)
[
    "attribute" => "created_at",
    "format" => ["date", "php:Y-m-d H:i:s"],
],

搜索:

1.若是 datetime 类型,dataProvider不用做修改

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

2.若是时间戳,则

首先,在模型文件中做如下修改

//原来的规则
public function rules()
{
    return [
        [['from_id', 'to_id', 'order_id', 'amount', 'status', 'created_at', 'updated_at'], 'integer'],
    ];
}

//修改成
public function rules()
{
    return [
        [['from_id', 'to_id', 'order_id', 'amount', 'status', 'updated_at'], 'integer'],
        [['created_at'],'safe'],
    ];
}
// 去掉原来规则里的 created_at 再增加一个安全的验证规则

然后,在搜索的模型xxxSearch增加一段代码,

//原代码
...
$this->load($params);

if (!$this->validate()) {
    // uncomment the following line if you do not want to return any records when validation fails
    // $query->where('0=1');
    return $dataProvider;
}

// grid filtering conditions
$query->andFilterWhere([
    'id' => $this->id,
    'charge_id' => $this->charge_id,
    'created_at' => $this->created_at,
    'updated_at' => $this->updated_at,
]);
...

dataProvider增加代码,并且注释掉原来的搜索代码

$this->load($params);

if (!$this->validate()) {
    // uncomment the following line if you do not want to return any records when validation fails
    // $query->where('0=1');
    return $dataProvider;
}
// 增加下面这段代码,增加下面这段代码,增加下面这段代码
if ($this->created_at) {
    // 可以根据业务需求封装

    $createdAt = strtotime($this->created_at);
    $times = strtotime(date('Y-m-d',$createdAt));
    $createdAtEnd = $times + 24*3600;

    $query->andWhere("created_at >= {$createdAt} AND created_at <= {$createdAtEnd}");
}


$query->andFilterWhere([
    'id' => $this->id,
    //...
    'pay_type' => $this->pay_type,
    'charge_id' => $this->charge_id,
    // 注释掉 created_at, 注释掉 created_at, 注释掉 created_at,
    // 'created_at' => $this->created_at,
    'updated_at' => $this->updated_at,
]);

到此为止,单个时间搜索的就完成了.

二.时间范围的搜索

1.安装yii2日期组件和时间组件

cd到项目根目录,在命令行或者终端运行

composer require kartik-v/yii2-widget-datetimepicker "*"

2.在searchmodel里面定义两个属性。

// 就是开始搜索时间和结束搜索时间
public $start_date;
public $end_date;

// 在rules()方法中加入
[['start_date', 'end_date'], 'string'],

// 在search()方法中 这个就是你搜索的字段
if ($this->start_date) {
    $start = strtotime($this->start_date);
    $query->andWhere("created_at >= {$start}");
}
if ($this->end_date) {
    $end = strtotime($this->end_date);
    $query->andWhere("created_at <= {$end}");
}

3.开启引入搜索表单(在生成的views里面的index.php中关闭注释)

<?php echo $this->render('_search', ['model' => $searchModel]); ?>

4.在views里面的—search.php中,

使用日期组件,引用 use kartik\datetime\DateTimePicker;

然后自定义widget.

(label是英文?去models的attributeLabels方法加上这两个属性就好.)

一种:(style不同)

<?php
use kartik\datetime\DateTimePicker;
?>

<div class="wechat-search">

<?php $form = ActiveForm::begin([
    'action' => ['index'],
    'method' => 'get',
]); ?>

<?= $form->field($model, 'start_date')->widget(DateTimePicker::classname(), [
'options' => ['placeholder' => ''],
'pluginOptions' => [
    'autoclose' => true,
    'todayHighlight' => true,
]
]); ?>
<?= $form->field($model, 'end_date')->widget(DateTimePicker::classname(), [
'options' => ['placeholder' => ''],
'pluginOptions' => [
    'autoclose' => true,
    'todayHighlight' => true,
]
]); ?>

另一种~

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\datetime\DateTimePicker;

/* @var $this yii\web\View */
/* @var $model backend\models\OrderPkSearch */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="order-dot-search">
    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>
    <div class="row" style="margin-bottom: 8px">
        <div class="col-sm-3">
            <?= $form->field($model, 'start_date')
                    ->widget(DateTimePicker::classname(), [
                        'options' => ['placeholder' => '2017-01-10 23:15','style'=>'float:left;'],
                        'pluginOptions' => [
                            'autoclose' => true,
                            'todayHighlight' => true,
                        ]
                    ])
                    ->label('开始时间'); ?>
        </div>
        <div class="col-sm-3">
            <?= $form->field($model, 'end_date')
                    ->widget(DateTimePicker::classname(), [
                        'options' => ['placeholder' => '2017-01-11 23:15','style'=>'float:left;'],
                        'pluginOptions' => [
                            'autoclose' => true,
                            'todayHighlight' => true,
                        ]
                    ])
                    ->label('结束时间'); ?>
        </div>
        <div class="form-group col-sm-2" style="margin-top: 25px;">
            <?= Html::submitButton('搜索', ['class' => 'btn btn-primary']) ?>
            <!-- <?= Html::resetButton('重置', ['class' => 'btn btn-default']) ?> -->
        </div>
    </div>
    <?php ActiveForm::end(); ?>
</div>

参考文章:

-http://www.yiichina.com/tutorial/604

-http://www.manks.top/yii2_datetimepicker.html

-http://www.manks.top/article/yii2_gridview_dateformat_search




导航