Deep Parekh Deep Parekh - 7 months ago 70
PHP Question

How to change date format in Yii

Hello I am newbie in Yii. I am saving data in a table which saves created_at date. But I am getting different date format which is in integer like "

1462422044
" . I want to change it to
dd-mm-yyyy h:i:s
. How to change this date format ?

My Master.php

public function behaviors() {
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
],
'value' => function() {
return time();
},
],
'user' => [
'class' => UserBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_by', 'updated_by'],
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_by',
],
'value' => function() {
return \Yii::$app->user->id == '' ? 0 : \Yii::$app->user->id;
},
],
];
}


My common/models/product.php

public function behaviors() {
return [
BlameableBehavior::className(),
TimestampBehavior::className(),
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['parent_id', 'created_by', 'updated_by'], 'integer'],
[['category_name'], 'required'],
[['created_at', 'updated_at'], 'safe'],
[['category_name'], 'string', 'max' => 100],
];
}

Answer

If your data type is datetime in database then you have to store your value convert in to this format "Y-m-d H:i:s" you can do this like this way. and created_at field means you want to store current date and time. so try below code hope it's work fine. here i my model variable is $model you need to replace with your variable name. Below is the one way if you want to store current datetime.

$model->created_at= date('Y-m-d H:i:s');

Here is the second way you can convert form your variable. suppose you will get your value in $currentDate then you can do this like below code.

$model->created_at= date('Y-m-d H:i:s',strtotime($currentDate));