尝试更改Carbon created_at日期的格式时,Laravel“发现意外的数据”错误

时间:2014-08-09 23:08:14

标签: laravel-4 php-carbon

当我尝试修改资源模型的默认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');

如果我从上面的代码中删除->format('F j, Y @ g:i A'),它可以正常工作,但它不是我想要的格式。问题是什么?我的应用程序中的其他地方几乎完全相同,但它没有错误。

更新 使用setToStringFormat('F j, Y @ g:i A')不会导致错误,但会返回null

7 个答案:

答案 0 :(得分:10)

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

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');
}

这允许我以我想要的格式使用created_atupdated_at

答案 1 :(得分:6)

我确实遇到了同样的问题,在我寻找答案的过程中,我遇到了How do you explain the result for a new \DateTime('0000-00-00 00:00:00')?

我决定将数据库中的datetime-columns更改为nullable,默认值为NULL,以防止字段具有值'0000-00-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();
});

答案 2 :(得分:5)

它不是碳问题,而是模型中setAttributegetAttribute之间的冲突。

答案 3 :(得分:2)

您不应尝试更改created_at的格式。它必须是一个Carbon对象。如果要以不同的格式显示created_at日期,则只需在输出时对其进行格式化。或者您可能想要创建一个更改格式的方法,以便您可以在需要时以不同的格式调用它。例如,将这样的方法添加到Resource类:

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

您还可以让该功能调整时区等。然后,您可以使用$tile->createdAtInMyFormat()created_at对象中获取特殊格式$tile

答案 4 :(得分:1)

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

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

答案 5 :(得分:0)

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

$model->update(['some_date' => '2020/1/1']); // bad
$model->update(['some_date' => '2020-1-1']); // good

提醒:如果您在模型上指定日期,那么Eloquent足够聪明,可以为您进行转换。

protected $dates = [ 'some_date' ];

答案 6 :(得分:0)

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

protected $casts = [
    'start_time' => 'time:h:i A',
    'end_time' => 'time:h:i A',
];

然后您可以使用 Carbon 或其他 PHP 原生函数进一步格式化它,例如
date('h:i A', strtotime($class_time->start_time)) // "09:00 AM"