Laravel 4 carbon 日期格式只更改一次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23349552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:26:20  来源:igfitidea点击:

Laravel 4 carbon date format change only once

laravelphp-carbon

提问by Chachoo Aguirre

Hello i am usng laravel 4 for a app page, i love the carbon date functions but i have a problem with a date format. i have the date format something like:

你好,我在应用程序页面上使用了 laravel 4,我喜欢碳日期功能,但我在日期格式方面遇到了问题。我有类似的日期格式:

dd/mm/yyyy

And i use :

我使用:

\Carbon\Carbon::createFromTimeStamp(strtotime(Auth::user()->created_at))->diffForHumans() 

to show how old its something, but that works fine when the date format its

显示它的年龄,但是当日期格式为它时效果很好

yyy-mm-dd

how can i only change one time the date format and not every time.

我怎样才能只更改一次日期格式而不是每次都更改。

回答by The Alpha

You may try this:

你可以试试这个:

$date = Auth::user()->created_at;
\Carbon\Carbon::createFromFormat('d/m/Y', $date)->diffForHumans();

Also you may try this (if you want to use createFromTimeStampmethod):

你也可以试试这个(如果你想使用createFromTimeStamp方法):

$date = str_replace('/', '-', Auth::user()->created_at);
\Carbon\Carbon::createFromTimeStamp(strtotime($date))->diffForHumans();

回答by kielabokkie

You can create an Accessor that will be used whenever you do echo $user->created_at:

您可以创建一个访问器,在您执行 echo 时将使用该访问器$user->created_at

public function getCreatedAtAttribute($attr)
{
    return Carbon::parse($attr)->diffForHumans();
}

More about Accessors: http://laravel.com/docs/eloquent#accessors-and-mutators

有关访问器的更多信息:http: //laravel.com/docs/eloquent#accessors-and-mutators

You can even put this in a BaseModel class and have all your Models extend the base class to automatically convert all created_at properties to your specified date format.

您甚至可以将它放在 BaseModel 类中,并让所有模型扩展基类以自动将所有 created_at 属性转换为您指定的日期格式。

回答by mzk

More easy global setup for date format in Laravel 4 : check this link

Laravel 4 中更简单的日期格式全局设置:检查此链接

In fact, it's super easy to globally change date format using Carbon's lib. All you have to do is create a BaseModel.php file into Model Folder, then add methods for Created_At and Updated_at -> set attributes. Then, extend your model with this BaseModel and all dates are displaying with your own format.

事实上,使用 Carbon 的 lib 全局更改日期格式非常容易。您所要做的就是在模型文件夹中创建一个 BaseModel.php 文件,然后为 Created_At 和 Updated_at 添加方法 -> 设置属性。然后,使用此 BaseModel 扩展您的模型,所有日期都以您自己的格式显示。

I hope you'll enjoy this discover...

我希望你会喜欢这个发现......