Laravel 4 “拉雷维尔”;“发现意外数据”;尝试更改在日期创建的碳的格式时出错

Laravel 4 “拉雷维尔”;“发现意外数据”;尝试更改在日期创建的碳的格式时出错,laravel-4,php-carbon,Laravel 4,Php Carbon,当我试图修改资源模型的默认created_at字段的格式时,出现以下错误: { "error":{ "type":"InvalidArgumentException", "message":"Unexpected data found. Unexpected data found. The separation symbol could not be found

当我试图修改资源模型的默认created_at字段的格式时,出现以下错误:

{  
   "error":{  
      "type":"InvalidArgumentException",
      "message":"Unexpected data found.
                 Unexpected data found.
                 The separation symbol could not be found
                 Unexpected data found.
                 A two digit second could not be found",
      "file":"\/var\/www\/html\...vendor\/nesbot\/carbon\/src\/Carbon\/Carbon.php",
      "line":359
   }
}
以下是产生上述错误的代码:

$tile = Resource::with('comments, ratings')->where('resources.id', '=', 1)->first();
$created_at = $tile->created_at;
$tile->created_at = $created_at->copy()->tz(Auth::user()->timezone)->format('F j, Y @ g:i A');
如果我从上面的代码中删除
->格式('fj,Y@g:ia')
,它可以正常工作,但不是我想要的格式。有什么问题吗?在我的应用程序的其他地方,我有几乎相同的代码,它可以正常工作

更新:
使用
setToString格式('fj,Y@g:ia')
不会导致错误,但会返回
null

您不应该尝试更改在
处创建的
的格式。它必须是一个碳物体。如果您想以不同的格式显示在
日期创建的
,则只需在输出时格式化即可。或者,您可能希望创建一个更改格式的方法,以便在需要其他格式时随时调用它。例如,将这样的方法添加到资源类:

public function createdAtInMyFormat()
{
   return $this->created_at->format('F j, Y @ g:i A');
}

您还可以使用该功能调整时区等。然后您可以使用
$tile->createdAtInMyFormat()
例如,从
$tile
对象在
处创建您的特殊格式

将以下代码添加到我的模型对我有用:

public function getCreatedAtAttribute($date)
{
    if(Auth::check())
        return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->copy()->tz(Auth::user()->timezone)->format('F j, Y @ g:i A');
    else
        return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->copy()->tz('America/Toronto')->format('F j, Y @ g:i A');
}

public function getUpdatedAtAttribute($date)
{
    return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('F j, Y @ g:i A');
}

这使我能够以我想要的格式使用在
处创建的和在
处更新的。

我确实遇到了同样的问题,在寻找答案的过程中我遇到了困难

我决定将数据库中的datetime列更改为NULL,默认值为NULL,以防止字段的值为“0000-00-00:00:00”

我在laravel 5中的迁移如下所示:

Schema::table('table', function($table)
{
    $table->dateTime('created_at')->nullable()->default(null)->change();
    $table->dateTime('updated_at')->nullable()->default(null)->change();
});

这不是碳排放问题,这是模型中的
setAttribute
getAttribute
之间的冲突。

我遇到了这个问题,这只是使用破折号而不是斜杠的问题

$model->update(['some_date' => '2020/1/1']); // bad
$model->update(['some_date' => '2020-1-1']); // good
提醒:如果您在模型上指定了日期,Eloquent足够聪明,可以为您转换它

protected $dates = [ 'some_date' ];

您需要在保存之前解析给定的日期 使用此代码

Carbon::parse($request->input('some_date'));

首先将其添加到您的模型中:

protected $casts = [
    'start_time' => 'time:h:i A',
    'end_time' => 'time:h:i A',
];
然后,您可以使用Carbon或其他Php本机函数对其进行进一步格式化,例如

date('h:ia',strottime($class\u time->start\u time))
/“09:00am”

我明白了。谢谢我用代码添加了我自己的答案,这对我来说更有效。