Laravel:显示时间戳字段的个人格式 [英] Laravel : display personal format of timestamps fields

查看:900
本文介绍了Laravel:显示时间戳字段的个人格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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



我想知道是否有办法去掉输出格式

解决方案

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

  public function getCreatedAtAttribute($ value)
{
返回日期('D m YH:i',strtotime($ value));
}

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



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



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

我还找到一个解决方案:

  \Carbon\Carbon: :setToStringFormat('D m YH:i'); 

您可以使用此行(以global.php为例),但会更改日期格式所有的应用程序。


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

解决方案

You can create an accessor function in your Post model.

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

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

More info here : 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.

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.

这篇关于Laravel:显示时间戳字段的个人格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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