laravel无法识别ISO8601格式的日期时间

时间:2017-12-31 11:16:50

标签: php mysql angularjs laravel laravel-5.5

假设我们的2015-02-05T14:50:55+01:00格式化日期时间来自 angularJs 客户端应用。

现在我想将它作为DATETIME MySQL保存在表格中。

我知道这是iso 8601格式的日期时间。因此,我将以下代码添加到我的模型中:

protected $dateFormat = 'DATE_ISO8601';

但是当我想用这个新字段更新我的模型时,我收到了这个错误:

A textual day could not be found
Meridian can only come after an hour has been found
The format separator does not match
The format separator does not match
The format separator does not match
The timezone could not be found in the database
Data missing {"userId":1,"email":"ahmadbadpey@gmail.com","exception":"[object] (InvalidArgumentException(code: 0): A textual day could not be found
Meridian can only come after an hour has been found
The format separator does not match
The format separator does not match
The format separator does not match
The timezone could not be found in the database
Data missing at D:\\wamp\\www\\zarsystem\\vendor\
esbot\\carbon\\src\\Carbon\\Carbon.php:582)
[stacktrace]
#0 D:\\wamp\\www\\zarsystem\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasAttributes.php(715): Carbon\\Carbon::createFromFormat('DATE_ISO8601', '2015-02-05T14:5...')

我尝试了其他一些预定义常量,例如DATE_ATOMDATE_W3C,......但是却有同样的错误。

我很困惑,我不知道该怎么办?

2 个答案:

答案 0 :(得分:1)

您可以这样做:

protected $dateFormat = 'c';
  

c是ISO 8601日期。

http://php.net/manual/en/function.date.php

此外,我认为这不是您想要的,因为您之前曾说过您希望在数据库Y-m-d H:i:s中以标准格式保留日期。

因此,您需要先添加an accessor以便在从数据库获取后再转换日期,然后a mutatorISO 8601转换回Y-m-d H:i:s,然后再保存到DB。

  

默认情况下,时间戳的格式为' Y-m-d H:i:s'。如果需要自定义时间戳格式,请在模型上设置$ dateFormat属性。此属性确定数据库中日期属性的存储方式,以及将模型序列化为数组或JSON时的格式

https://laravel.com/docs/5.5/eloquent-mutators#date-mutators

答案 1 :(得分:0)

DATE_ISO8601常量,在DateTime类中定义,您尝试使用格式掩码字符串'DATE_ISO8601'

你应该能够做到

protected $dateFormat = \DateTime::DATE_ISO8601;

但是,这种格式与ISO-8601不兼容,但出于向后兼容的原因,这种格式是这样的。所以最好使用ATOM常量

protected $dateFormat = \DateTime::ATOM;