Yii2视图DateTime格式(d-m-Y H:i:s),但是当DB更改格式保存/更新到Y-m-d H:i:s。

时间:2022-06-29 21:27:12

I'm Using Kartik DateTimePicker Extension

我使用Kartik DateTimePicker扩展。

<?= $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 (like 24-09-2015 11:21:10)

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 (like 2015-09-24 11:21:10)

i:s(如2015-09-24 11:21:10)

How can I change the date format on save/update of record

如何更改保存/更新记录的日期格式?

4 个解决方案

#1


3  

Need to just add this code before save/update model in controller.

需要在控制器中保存/更新模型之前添加此代码。

like,

就像,

// ICU format
$model->Created = Yii::$app->formatter->asDate($_POST['modelName']['Created'], 'yyyy-MM-dd HH:mm:ss'); // 2014-10-06 15:22:34

OR

// PHP date()-format
$model->Created = Yii::$app->formatter->asDate($_POST['modelName']['Created'], 'php:Y-m-d H:i:s'); // 2014-10-06 15:22:34

For more information refer this link

更多信息请参考此链接。

#2


2  

Finally I found the answer using AttributeBehavior.

最后,我使用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));
            },
        ],
    ];
}

My Model Class

我的模型类

    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',
        ];
    }
}

If input format is d/m/Y then you need to replace the "/" by "-"

如果输入格式是d/m/Y,那么你需要将“/”改为“-”

like: input date(created): 10/09/2015

如:输入日期(创建):10/09/2015

date('Y-m-d H:i:s', strtotime(str_replace("/","-",$this->created)));

#3


0  

use in active form

使用活动形式

'clientOptions' => ['alias' => 'dd-mm-yyyy'],

'clientOptions' => ['alias' => 'dd-mm-yyy '],

use in active form

使用活动形式

echo MaskedInput::widget([
'name' => 'input-31',
'clientOptions' => ['alias' =>  'date']]);

use class

使用类

Class yii\widgets\MaskedInput

类yii \ \ MaskedInput小部件

Example

例子

<?= $form->field($model, 'date_of_birth')->widget(\yii\widgets\MaskedInput::className(), [
    'name' => 'input-31',
    'clientOptions' => ['alias' =>  'dd-mm-yyyy'],        ]) ?>   

#4


0  

I have simple code, in behavior:

我有简单的代码,在行为上:

 public function behaviors() {
    return [
       [ 'class' => \yii\behaviors\TimestampBehavior::className(),
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
            ],
            // if you're using datetime instead of UNIX timestamp:
             'value' => new Expression('NOW()'),
       ]
    ];
}

for rules:

规则:

 public function behaviors() {
    return [
       [ 'class' => \yii\behaviors\TimestampBehavior::className(),
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
            ],
            // if you're using datetime instead of UNIX timestamp:
             'value' => new Expression('NOW()'),
       ]
    ];
}

#1


3  

Need to just add this code before save/update model in controller.

需要在控制器中保存/更新模型之前添加此代码。

like,

就像,

// ICU format
$model->Created = Yii::$app->formatter->asDate($_POST['modelName']['Created'], 'yyyy-MM-dd HH:mm:ss'); // 2014-10-06 15:22:34

OR

// PHP date()-format
$model->Created = Yii::$app->formatter->asDate($_POST['modelName']['Created'], 'php:Y-m-d H:i:s'); // 2014-10-06 15:22:34

For more information refer this link

更多信息请参考此链接。

#2


2  

Finally I found the answer using AttributeBehavior.

最后,我使用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));
            },
        ],
    ];
}

My Model Class

我的模型类

    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',
        ];
    }
}

If input format is d/m/Y then you need to replace the "/" by "-"

如果输入格式是d/m/Y,那么你需要将“/”改为“-”

like: input date(created): 10/09/2015

如:输入日期(创建):10/09/2015

date('Y-m-d H:i:s', strtotime(str_replace("/","-",$this->created)));

#3


0  

use in active form

使用活动形式

'clientOptions' => ['alias' => 'dd-mm-yyyy'],

'clientOptions' => ['alias' => 'dd-mm-yyy '],

use in active form

使用活动形式

echo MaskedInput::widget([
'name' => 'input-31',
'clientOptions' => ['alias' =>  'date']]);

use class

使用类

Class yii\widgets\MaskedInput

类yii \ \ MaskedInput小部件

Example

例子

<?= $form->field($model, 'date_of_birth')->widget(\yii\widgets\MaskedInput::className(), [
    'name' => 'input-31',
    'clientOptions' => ['alias' =>  'dd-mm-yyyy'],        ]) ?>   

#4


0  

I have simple code, in behavior:

我有简单的代码,在行为上:

 public function behaviors() {
    return [
       [ 'class' => \yii\behaviors\TimestampBehavior::className(),
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
            ],
            // if you're using datetime instead of UNIX timestamp:
             'value' => new Expression('NOW()'),
       ]
    ];
}

for rules:

规则:

 public function behaviors() {
    return [
       [ 'class' => \yii\behaviors\TimestampBehavior::className(),
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
            ],
            // if you're using datetime instead of UNIX timestamp:
             'value' => new Expression('NOW()'),
       ]
    ];
}