How to filter date field in yii2

2019-07-11 05:00发布

问题:

I want to filter Date column like 3 months ago, 6 months ago, 1 year ago. I have created a dropdown in search field of gridview as given below.

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

and in modelsearch I want to search like...

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

but I can't understand what should be there in place of today 3monthsago ? how to calculate and pass this variables in query??

回答1:

Add this to your 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]);
}


标签: date yii2