如何过滤yii2中的日期字段

时间:2017-12-08 05:54:01

标签: date yii2

我想过滤日期列,如3个月前,6个月前,1年前。 我在gridview的搜索字段中创建了一个下拉列表,如下所示。

[
    'attribute' => 'modified',
    'value'     => 'name',
    'filter'    => array("ID1" => "Before Three months",
                         "ID2" => "Before six months",
                         "ID"  => "Before Twelve months",),
],

在modelsearch中我想搜索...

if (($this->modified) == "ID1"){
    $query->andFilterWhere(['between', $this->modified, 'today', '3monthsago']);
} 

但是我无法理解今天应该有什么代替3monthsago? 如何在查询中计算并传递这些变量?

1 个答案:

答案 0 :(得分:0)

将此添加到您的modelsearch

$today = date('Y-m-d H:i:s',time());
if (($this->modified)=="ID1"){
    $endDate = date('Y-m-d H:i:s', strtotime('-3 months'));
    $query->andFilterWhere(['between', 'contacts.modified', $today, $endDate]);
}elseif (($this->modified)=="ID2") {
    $endDate = date('Y-m-d H:i:s', strtotime('-6 months'));
    $query->andFilterWhere(['between', 'contacts.modified', $today, $endDate]);
}elseif (($this->modified)=="ID") {
    $endDate = date('Y-m-d H:i:s', strtotime('-12 months'));
    $query->andFilterWhere(['between', 'contacts.modified', $today, $endDate]);
}