【问题标题】:How to store my datetime as a date in my database [duplicate]如何将我的日期时间作为日期存储在我的数据库中[重复]
【发布时间】:2019-04-01 16:08:46
【问题描述】:

目标:我想将一些数据从 api 保存到我的数据库中,日期在 api 中如下所示:

"utcDate": "2018-10-28T13:30:00Z"

我尝试在我的迁移中使用 datetime,但我收到错误,指出这不是正确的格式。

$table->datetime('date');

我的错误:

PDOException::("SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2018-10-20T11:30:00Z' for column 'date' at row 1")

还有其他方法可以将此日期作为日期存储在我的数据库中吗?

【问题讨论】:

  • NOT是个骗子——Laravel/MySQL 不需要将 Eloquent 模型转换为 Unix 时间戳。当提供 DateTime 对象时,Eloquent 会自动格式化数据库的值,因此除了首先将日期字符串转换为 DateTime 对象之外,无需进行任何转换。

标签: php mysql laravel date


【解决方案1】:

在插入值之前,您需要使用DateTime 将其转换为date 形式datetime,这会导致错误,因为$table->datetime('date'); 不适合您将其转换为date 格式。您也可以使用 MYSQL DATE() 将其从 datetime 转换为 date

<?php

$datetime = "2018-10-28T13:30:00Z";
$date = new DateTime($datetime);
echo $date->format('Y-m-d');
?>

<?php
$datetime = "2018-10-28T13:30:00Z";
echo date("Y-m-d", strtotime($datetime));
?>

【讨论】:

    【解决方案2】:

    我认为这个查询很简单,通过使用 MySQL 中的 DATE() 方法来完成

        INSERT INTO `test`
        (`createdAt`)
        VALUES
        (DATE('2018-01-01 07:00:01'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-26
      • 2011-02-04
      • 2014-01-16
      • 2014-08-29
      • 2017-05-31
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多