Laravel“发现意外数据"尝试更改 Carbon created_at 日期的格式时出错 [英] Laravel "Unexpected data found" error when trying to change format of Carbon created_at date

查看:24
本文介绍了Laravel“发现意外数据"尝试更改 Carbon created_at 日期的格式时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I try to modify the format of the default created_at field of my Resource model, I get the following error:

{  
   "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
   }
}

这是产生上述错误的代码:

Here is the code that produced the above error:

$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') ,它可以正常工作,但它不是我想要的格式.问题可能是什么?我的应用程序的其他地方有几乎相同的代码,它可以正常工作.

If I remove ->format('F j, Y @ g:i A') from the above code, it works fine, but it's not in the format I want. What could the problem be? I have almost identical code elsewhere in my app and it works without error.

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

UPDATE: Using setToStringFormat('F j, Y @ g:i A') does not cause an error, but returns null.

推荐答案

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

Adding the following code to my model worked for me:

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

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

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

This allows me to use created_at and updated_at in the format I want.

这篇关于Laravel“发现意外数据"尝试更改 Carbon created_at 日期的格式时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆