在laravel字段中显示时间戳的日期部分

问题描述:

I have a table data value in my laravel blade:

<td>{{$events->updated_at}}</td>

which just reads from a database timestamp value. It works and displays as it should but the controller is reading the full timestamp, which we need, but in this table data cell I only want to display the date portion.

So instead of 2017-12-27-00:00:00, I just want to show 2017-12-27.

Is there a special way I should go about this in a laravel blade?

我的laravel刀片中有一个表数据值: p>

 &lt; td&gt; {{$ events-&gt; updated_at}}&lt; / td&gt; 
  code>  pre> 
 
 

只是从数据库中读取 timestamp em >价值。 它工作和显示应该是,但控制器正在读取我们需要的完整时间戳,但在此表中数据单元格我只想显示日期部分。 p>

所以而不是2017年 -12-27-00:00:00,我只想展示2017-12-27。 p>

我是否应该采用特殊方式在laravel刀片上进行此操作? p> div>

All the timestamps in an Eloquent object use the Carbon class, making formatting easier. So all you have to do is use the Carbon format functions:

<td>{{$events->updated_at->toDateString()}}</td>

The updated_at attribute should be cast to a Carbon object already before it’s passed to the view, so you can just do

{{ $events->updated_at->toDateString() }}

If that doesn’t work, in your model do this:

protected $dates = [‘updated_at’];

Since it's a Carbon instance, you can use any of it's methods:

{{ $events->updated_at->toDateString() }}

Or:

{{ $events->updated_at->format('Y-m-d') }}

Alternatively, you can create a new accessor:

public function getUpdatedAttribute()
{
    return $this->updated_at->toDateString();
}

And use it in Blade:

{{ $events->updated }}