Answer the question
In order to leave comments, you need to log in
How to set date formatting rules in YII2 model?
Hello.
There is an ActiveRecord model containing the created_at field, the field type in the database is timestamp.
I need to select the desired records and send them as json, that is, like this:
\Yii::$app->response->format = Response::FORMAT_JSON;
$consultations = Consultation::find()->orderBy('id DESC')->limit(5)->asArray()->all();
return $consultations;
created_at
looks like "2017-06-09 16:14:09", and I need a short entry "06/09/17". formattedDate
, which would take data from created_at
and format it as I need. Answer the question
In order to leave comments, you need to log in
If you need to make such transformations everywhere, then you can put the logic in afterFind.
If not everywhere but often, make a getter in the model that makes the necessary transformations, for example:
public function getShortDate(){
return \Yii::$app->formatter->asDate($this->created_at, 'short');
}
$consultations = Consultation::find()->orderBy('id DESC')->limit(5)->all();
$data = ArrayHelper::toArray($consultations [
'app\models\Consultation' => [
'date' => function ($model) {
return \Yii::$app->formatter->asDate($model->created_at, 'short');
},
'date2' => 'shortDate' //это вариант если геттер есть, который выше описал
],
]);
\Yii::$app->response->format = Response::FORMAT_JSON;
return $data
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question