Laravel 5.2:如何显示这样的时间?

时间:2016-05-08 19:25:08

标签: php laravel

我正在使用Laravel 5.2,我想像这样展示文章的创作时间:

created_at                               displaying
in  1  day                                today
2-10 days                                 (2-10) days ago
>10  days                                  show creation date directly

怎么做?
提前致谢!

编辑

控制器:

  public function show($id)
    {
        $article = Article::findOrFail($id);
        return view('show', compact('article'));
    }

观点:

<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>

我应该在哪里使用Carbon的{​​{1}}?

5 个答案:

答案 0 :(得分:2)

您可以为自定义属性

定义accessor
<?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;
        }
    }

}

然后在视图中

<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>

答案 1 :(得分:1)

你有没有检查过碳差异对人类的影响?

http://carbon.nesbot.com/docs/#api-humandiff

由于created_at字段默认为Carbon实例,因此您可以像这样调用碳方法:

$post->created_at->diffForHumans()

答案 2 :(得分:1)

你可以尝试\Carbon\Carbon类和人类差异,就像这里:

http://carbon.nesbot.com/docs/#api-humandiff

答案 3 :(得分:1)

$ diff = $ post-&gt; created_at-&gt; diffInDays()

$diff = $post->created_at->diffInDays()

现在逻辑:

if($diff == 1)
  echo 'today';
elseif($diff >1 && $diff <= 10)
  echo "$diff days ago";
else
  echo $diff->created_at;

注意这仅适用于您的特定情况。否则你应该使用Carbon&#39; s diffForHumans()

答案 4 :(得分:0)

这里是crabon的教程:More

 $dt     = Carbon::now();
 $past   = $dt->subMonth();
 $future = $dt->addMonth();

 echo $dt->subDays(10)->diffForHumans();     // 10 days ago
 echo $dt->diffForHumans($past);             // 1 month ago
  echo $dt->diffForHumans($future);           // 1 month before