显示当前系统日期和时间

时间:2017-09-02 18:11:29

标签: php yii2

如何在表单上显示我当前的系统(PC)时间

现在我正在使用datetimepicker,我想尝试当我要以某种形式创建某些内容时,“time_start”将自动获得我在PC上使用的时间。

<?= $form->field($model, 'time_start')->widget(
    DateTimePicker::className(), [
        'options'       => [ 'placeholder' => 'Render Time' ],
        'pluginOptions' => [ 'autoclose' => true, ]
    ]
); ?>

1 个答案:

答案 0 :(得分:1)

您可以在调用渲染之前直接在控制器中将值分配给$ model-&gt; time_start ..

因此您可以使用php functin在controllerAction中管理问题,以便分配您需要的值,例如在actionCreate中

public function actionCreate()
{
    $model = new MyModel();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        //  assign the the date and time of the server that the code runs on.
        $model->time_start =  date("d-m-Y H:i:s");
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

或者如果您需要特定的时区

public function actionCreate()
{
    $model = new MyModel();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        //  assign the the date and time of the server that the code runs on.
        //  
        $my_date = new DateTime("now", new DateTimeZone('America/New_York') );

        $model->time_start =   $my_date;
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}