[英]Laravel 5.2 :How to display time like this?
I am using Laravel 5.2, I want to show the article's creation time like this: 我正在使用Laravel 5.2,我想像这样展示文章的创建时间:
created_at displaying
in 1 day today
2-10 days (2-10) days ago
>10 days show creation date directly
How to do it? 怎么做?
Thanks in advance! 提前致谢!
edit: 编辑:
controller: 控制器:
public function show($id)
{
$article = Article::findOrFail($id);
return view('show', compact('article'));
}
view: 视图:
<div class="card">
<div class="card-block">
<h4 class="card-title">{{$article->title}}</h4>
<p class="card-text">{{$article->content}}</p>
<p class="card-text"><small class="text-muted">{{$article->created_at}}</small></p>
</div>
</div>
Where should I use Carbon
's diffForHumans()
? 我应该在哪里使用Carbon
的diffForHumans()
?
You can define accessor for custom attribute 您可以为自定义属性定义访问者
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class User extends Model
{
public function getPrettyCreatedAtAttribute()
{
$now = Carbon::now();
$age = $this->created_at->diffInDays($now);
if ($age < 2) {
return 'today';
}
elseif ($age < 10) {
return '(2-10) days ago';
}
else {
return $this->created_at;
}
}
}
Then in view 然后在视野中
<div class="card">
<div class="card-block">
<h4 class="card-title">{{$article->title}}</h4>
<p class="card-text">{{$article->content}}</p>
<p class="card-text"><small class="text-muted">{{$article->pretty_created_at}}</small></p>
</div>
</div>
Have you check put the Carbon diff for humans feature? 你有没有检查过碳差异对人类的影响?
http://carbon.nesbot.com/docs/#api-humandiff http://carbon.nesbot.com/docs/#api-humandiff
Since the created_at
field is a Carbon instance by default you can call carbon methods on it like so: 由于created_at
字段默认为Carbon实例,因此您可以像这样调用碳方法:
$post->created_at->diffForHumans()
You can try \\Carbon\\Carbon
class and diff for human like here: 你可以试试\\Carbon\\Carbon
class和diff for human就像这里:
http://carbon.nesbot.com/docs/#api-humandiff http://carbon.nesbot.com/docs/#api-humandiff
$diff = $post->created_at->diffInDays() $ diff = $ post-> created_at-> diffInDays()
$diff = $post->created_at->diffInDays()
Now the logic: 现在逻辑:
if($diff == 1)
echo 'today';
elseif($diff >1 && $diff <= 10)
echo "$diff days ago";
else
echo $diff->created_at;
Note this is only for your particular situation. 请注意,这仅适用于您的特定情况。 Otherwise you should use Carbon' s diffForHumans()
否则你应该使用Carbon的diffForHumans()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.