Laravel:显示时间戳字段的个人格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25060750/
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:52:57  来源:igfitidea点击:

Laravel : display personal format of timestamps fields

datetimelaravel

提问by Lolo

In my project I used this code to format timestamps fields

在我的项目中,我使用此代码来格式化时间戳字段

date('D m Y  H:i', strtotime($post->created_at))

But as I have many places and fields to display it's a bit boring, and if I need to change the format it won"t be easy to maintain.

但是因为我有很多地方和字段来显示它有点无聊,如果我需要改变格式,它不会很容易维护。

I'd like to know if there is a way to decalre the output format

我想知道是否有办法对输出格式进行 decalre

回答by Needpoule

You can create an accessor function in your Post model.

您可以在 Post 模型中创建访问器函数。

public function getCreatedAtAttribute($value)
{
    return date('D m Y H:i', strtotime($value));
}

This way, each time you'll call $post->created_atit will display the date returned by your accessor instead of the default value.

这样,每次调用$post->created_at它时都会显示访问器返回的日期而不是默认值。

More info here : http://laravel.com/docs/eloquent#accessors-and-mutators

更多信息:http: //laravel.com/docs/eloquent#accessors-and-mutators

If you don't want this function in all your models your can create a BaseModel class and make your models extend this BaseModel class.

如果您不想在所有模型中使用此函数,您可以创建一个 BaseModel 类并使您的模型扩展此 BaseModel 类。

I also found an other solution:

我还找到了另一个解决方案:

\Carbon\Carbon::setToStringFormat('D m Y H:i');

You can use this line (in global.php for exemple) but it will change the date format in all the application.

您可以使用这一行(例如在 global.php 中),但它会更改所有应用程序中的日期格式。