更改Yii dateField的日期格式

时间:2015-11-05 12:07:40

标签: php date yii datepicker

我想在Yii中显示日期选择器并以“YYYY-MM-DD”格式获取日期,以便我可以保存在我的数据库中。我使用了以下代码,但它以“MM / DD / YYYY”格式提供日期,在保存数据库时抛出错误,因为这不是日期。

查看代码:

<div class="row">
    <?php echo $form->labelEx($model,'datecreated'); ?>
    <?php echo $form->dateField($model,'datecreated'); ?>

    <?php echo $form->error($model,'datecreated'); ?>
</div>

模态代码:

<?php

public function tableName()
{
    return 'admin';
}

public function rules()
{

    return array(
        array('datecreated', 'type', 'type' => 'date', 'message' => '{attribute}: is not a date!','dateFormat'=>'YYYY-MM-DD'),
        array('datecreated','safe', 'on'=>'search'),
    );
}

public function attributeLabels()
{
    return array(
        'datecreated' => 'Birthdate',
    );
}

public function search()
{

    $criteria=new CDbCriteria;
    $criteria->compare('datecreated',$this->datecreated,true);

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
}
?>

2 个答案:

答案 0 :(得分:1)

您可以在模型中使用beforeSave功能:

protected function beforeSave()
{
    // convert when storing in db
    $this->datecreated = date('Y-m-d', strtotime($this->datecreated));

    return parent::beforeSave();
}

如果您想以mm / dd / yyyy格式显示日期,请在模型中使用afterFind功能:

protected function afterFind()
{
    // convert the date back to mm/dd/yyyy format while viewing
    $this->datecreated = date('m/d/Y', strtotime($this->datecreated));

    parent::afterFind();
}

或者,您可以在$model->save();之前转换控制器中的日期格式:

public function actionCreate()
{
    $model = new Admin();
    if(isset($_POST['Admin']))
    {
        $model->attributes=$_POST['Admin'];
        $model->datecreated = date('Y-m-d', strtotime($model->datecreated));
        ......
        $model->save();
        ......
    }
    ......
}

答案 1 :(得分:0)

您也可以使用CJuiDatePicker小部件:

select proper( LastName ) as properLastName 
from table 

您还可以使用CDateValidator添加验证规则:

$this->widget('zii.widgets.jui.CJuiDatePicker', array(
    'model'=>$model,
    'attribute'=>'datecreated',
    // jQuery datepicker plugin options
    'options' => array(
        'showAnim' => 'fold',
        'dateFormat'=>'yyyy-mm-dd',
    ),
    'htmlOptions' => array(
     ),
));

感谢。