【问题标题】:We have a user inputting a date in m/d/Y and i'm trying to get it into Y/m/d to save into MYSQL我们有一个用户在 m/d/Y 中输入日期,我正试图将其输入 Y/m/d 以保存到 MYSQL
【发布时间】:2020-07-08 16:19:06
【问题描述】:

我们让用户在 glyphicon-calender 中输入 m/d/Y 中的日期,我们正在尝试将它输入到 Y/m/d 中,以便像这样用于 MYSQL,但它不会验证或保存.

 // Normalize datetime input
        if (!empty($this->requested_ship_date)) {
            $date = new \DateTime($this->requested_ship_date);
            $this->requested_ship_date = $date->format('Y-m-d H:i:s');
        }

我们收到一个数据库异常,表示事务处于非活动状态,错误来自控制器中的这一行

 if (Yii::$app->request->post() && $model->validate() && $model->save())

这里是输入代码,

 <?= $form->field($model->order, 'requested_ship_date', [
     'inputTemplate' =>
         '<div class="input-group date"><span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>{input}</div>',
                        ])->textInput([
                            'value' => (isset($model->order->requested_ship_date)) ? Yii::$app->formatter->asDate($model->order->requested_ship_date) : '',
                        ]) ?>

【问题讨论】:

  • $model-&gt;save()ActiveRecord::save() 方法还是被覆盖?

标签: php mysql datetime yii2


【解决方案1】:

您需要使用 DateTime 类中的 createFromFormat 方法。

// Normalize datetime input
if (!empty($this->requested_ship_date)) {
    $newDateTime = DateTime::createFromFormat('m/d/Y', $this->requested_ship_date);
    $this->requested_ship_date = $newDateTime->format('Y-m-d');
}

根据需要使用格式。

【讨论】:

  • 仍然出现同样的数据库异常错误,提交事务失败:事务处于非活动状态。
  • 它没有生成 SQL 代码,因为它没有通过模型验证,beforeValidate() 是否适合使用,如果适合,在哪里?
  • 查看调试器日志,它确实转换为 SQL 的正确格式,但随后模型由于验证错误而失败
  • 请。检查验证规则,它在寻找什么?
  • $return[] = [['requested_ship_date'], 'date'];
猜你喜欢
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 1970-01-01
  • 2021-03-09
  • 2021-11-26
  • 1970-01-01
相关资源
最近更新 更多