-2

$query->andFilterWhere(['like', 'date_of_birth', date('d-m-Y',strtotime($this->date_of_birth))]);

It's not working..

1 Answers1

1

¿Are you using MySQL? then the date format is: YYYY-MM-DD. This is how MySQL works and you cannot change that.

You can show the date in the format you want on your website and your forms, but you have to pass it to MYSQL as MYSQL expects to receive it. So what you should do is the following:

In your model class:

public function beforeSave($insert) {

    /* for example if my form date format is: dd-mm-yyyy 
    You must change it for yyyy-mm-dd before saving into DDBB */

    if (!empty($this->date_of_birth )) {
        $this->date_of_birth = Yii::$app->formatter->asDate($this->date_of_birth, 'php:Y-m-d');
    }

    return parent::beforeSave($insert);

}  

Check the docs for more info:

https://www.yiiframework.com/doc/api/2.0/yii-db-baseactiverecord#beforeSave()-detail

In order to show this date again in your forms and views:

<?php    
    $model->date_of_birth = !empty($model->date_of_birth) ? Yii::$app->formatter->asDate($model->date_of_birth, 'php:d-m-Y') : null;    
?>

UPDATED:

To make the filters work in (for example) the gridview when you have a formatted date, you should modify the comparison in your YourModelSearch.php model class:

From this:

$query->andFilterWhere(['date_of_birth' => $this->date_of_birth]);

To this:

/* Change the format to MySQL Date Format when compares */
$query->andFilterWhere(['date_of_birth' => Yii::$app->formatter->asDate($this->date_of_birth, 'php:Y-m-d')]);

And in your config/web.php you should have something like this:

'components' => [
    ...
    'formatter' => [
        'class' => 'yii\i18n\Formatter',
        'timeZone' => 'Europe/London',
        'defaultTimeZone' => 'Europe/London',
        'dateFormat' => 'd/M/Y',
        'datetimeFormat' => 'd/M/Y H:m',
        'timeFormat' => 'H:m:s',
        'decimalSeparator' => ',',
        'thousandSeparator' => '',
        'currencyCode' => 'EUR',
        'locale'=>'es_ES'
    ],
    ...
]

And never use the LIKE comparer with Date types.

Dan A.S.
  • 524
  • 5
  • 20
  • hello sir..!Thanks for ur reply...But this is not my question... I've made the date format(d-m-Y) into my form,view and index.php pages.It shows date into d-m-Y which is that i was expected to show...But now my ques is,I cannot able to search date in d-m-Y format in index page search box instead it shows the date results for Y-m-d format search..! It needs to show the results for d-m-Y search format. what changes should i need to make that in serach.php? – Sanjay Rahul May 25 '21 at 08:17
  • Take a look at my answer update. – Dan A.S. May 25 '21 at 10:51
  • Thank You @Dan A.S. for ur help! It worked! – Sanjay Rahul May 25 '21 at 11:45