How to filter date field in yii2

旧街凉风 提交于 2019-12-24 01:15:58

问题


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]);
}


来源:https://stackoverflow.com/questions/47708512/how-to-filter-date-field-in-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!