14

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

4

7 回答 7

14

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

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格式。

于 2014-08-10T16:19:14.623 回答
6

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

我决定将数据库中的日期时间列更改为可空值,默认值为 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();
});
于 2015-06-22T12:35:12.667 回答
6

setAttribute这不是碳问题,而是模型中的或之间的冲突getAttribute

于 2015-07-04T05:25:08.637 回答
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对象中获取特殊格式。

于 2014-08-10T00:11:36.227 回答
1

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

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"

于 2021-02-16T06:31:31.723 回答
1

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

Carbon::parse($request->input('some_date'));
于 2020-03-10T10:00:58.697 回答
0

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

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

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

protected $dates = [ 'some_date' ];
于 2020-01-04T19:24:43.827 回答