DATE_FORMAT in query builder


I’m having trouble using the Query builder with the MySQL DATE_FORMAT function.

for instance, if I’m building a query like this:


        $month_year = new \yii\db\Expression("DATE_FORMAT(`news_date`, '%Y-%m')");

        $months = NewsItem::find()



for some reason, Yii2 quotes the format string, like so:

SELECT DATE_FORMAT(`NewsDate`, `'%Y-%m')` 

note the syntax-breaking backticks around:


has anyone successfully used DATE_FORMAT with Query builder?

I can, and will use straight SQL here, but I thought I’d ask the Yii community about it.


Does the same happen when you use it like this?


Nope - that solves it.

I just realized this is in the documentation:

“Note that if you are selecting an expression like CONCAT(first_name, ’ ', last_name), you should use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.”

thanks for your help, and sorry to ask a question I could have figured out myself.


I used as like below

$query->select(["DATE_FORMAT(created_at, '%d-%m-%Y') as c_date"']) 

and its works fine