Yii2 查看日期时间格式 (d-m-Y H:i:s) 但在 DB 中保存/更新时将格式更改为 Y-m-d H:i:s [英] Yii2 View DateTime Format (d-m-Y H:i:s) But When Save/update in DB Change format to Y-m-d H:i:s
问题描述
我正在使用 Kartik DateTimePicker 扩展
I'm Using Kartik DateTimePicker Extension
<?= $form->field($model, 'Created')->widget(DateTimePicker::classname(),[
'model' => $model,
'attribute' => 'Created',
'name' => 'Created',
'options' => ['placeholder' => 'Select Created'],
'pluginOptions' => [
'format' => 'dd-mm-yyyy hh:ii:ss',
'todayHighlight' => true
]
])
?>
用户填写创建日期,格式为
User fill the Create Date the format is
d-m-Y H:i:s(如 24-09-2015 11:21:10)
但是当记录保存到数据库然后创建日期格式更改为
But when record save to database then Create Date Format change to
Y-m-d H:i:s(如 2015-09-24 11:21:10)
如何更改保存/更新记录的日期格式
How can I change the date format on save/update of record
推荐答案
最后我使用 AttributeBehavior 找到了答案.
Finally I found the answer using AttributeBehavior.
在我的模型类中,我编写了行为代码:
In my model class I've write the behaviors code:
public function behaviors()
{
return [
[
'class' => AttributeBehavior::className(),
'attributes' => [
// update 1 attribute 'created' OR multiple attribute ['created','updated']
ActiveRecord::EVENT_BEFORE_INSERT => ['created','updated'],
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated',
],
'value' => function ($event) {
return date('Y-m-d H:i:s', strtotime($this->Created));
},
],
];
}
我的模型类
namespace frontend\models;
use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\AttributeBehavior;
/**
* This is the model class for table "product".
*
* @property integer $id
* @property integer $product_id
* @property string $product_name
* @property string $created
* @property string $updated
*/
class Product extends ActiveRecord
{
public $csv_file;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'product';
}
public function behaviors()
{
return [
[
'class' => AttributeBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created','updated'], // update 1 attribute 'created' OR multiple attribute ['created','updated']
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated', // update 1 attribute 'created' OR multiple attribute ['created','updated']
],
'value' => function ($event) {
return date('Y-m-d H:i:s', strtotime($this->LastUpdated));
},
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'product_id', 'product_name', created, updated], 'required'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'product_id' => 'Product ID',
'product_name' => 'Product Name',
'created' => 'Created',
'updated' => 'Updated',
];
}
}
如果输入格式为d/m/Y,则需要将/"替换为-"
If input format is d/m/Y then you need to replace the "/" by "-"
喜欢:输入日期(创建):10/09/2015
like: input date(created): 10/09/2015
date('Y-m-d H:i:s', strtotime(str_replace("/","-",$this->created)));
这篇关于Yii2 查看日期时间格式 (d-m-Y H:i:s) 但在 DB 中保存/更新时将格式更改为 Y-m-d H:i:s的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!