Home > Backend Development > PHP Tutorial > Laravel时间显示问题

Laravel时间显示问题

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:09:33
Original
1497 people have browsed it

Laravel时间显示问题,我想让时间这样显示:

比如:一篇文章的发表时间:

<code>**距离现在时间**      **显示格式**
10天                   直接显示日期</code>
Copy after login
Copy after login

应该怎么做呢?

回复内容:

Laravel时间显示问题,我想让时间这样显示:

比如:一篇文章的发表时间:

<code>**距离现在时间**      **显示格式**
10天                   直接显示日期</code>
Copy after login
Copy after login

应该怎么做呢?

Laravel 本身有对 Carbon 的完美支持,巧妙的利用就可以达到很好的效果:

首先:

在你的app/Providers/AppServiceProvider.php中添加\Carbon\Carbon::setLocale('zh');这一行到boot()方法当中,(为了中文化显示)

<code> public function boot()
    {
        \Carbon\Carbon::setLocale('zh');
    }</code>
Copy after login

第二:

ArticleModel 中添加下面的方法:

<code>  public function getCreatedAtAttribute($date)
    {
        if (Carbon::now() addDays(10)) {
            return Carbon::parse($date);
        }

        return Carbon::parse($date)->diffForHumans();
    }
   </code>
Copy after login

这里注意到使用到了 Laravel 的 getXXXAttribute() 的特性,如果你是其他的字段,比如published_at,方法应该写成 getPublishedAtAttribute($date),别忘了在Article头部use Carbon\Carbon;

最后:

直接显示你的日期就好:

<code>$article = \App\Article::find(7);

{{ $article->created_at }}; // 视图中直接显示</code>
Copy after login

更多 Laravel 的讨论学习,请到我的小站:https://laravist.com

亲测: Laravel 5.1 和 5.2 都OK

时间问题前端处理可能会对服务器压力小点,有一个moment.js你可以试一下
moment.js

public function formatDate($time = 0){
    $tmp = time() - $time;
    if($tmp && $tmp <= 60 * 60){
        return ceil($tmp / 60) + 1 . '分钟前';
    }elseif($tmp > 60 * 60 && $tmp < 60 * 60 * 24){
        return ceil($tmp / 60 / 60) + 1 . '小时前';
    }elseif($tmp > 60 * 60 * 24 && $tmp < 60 * 60 * 24 * 10){
        return ceil($tmp / 60 / 60 / 24) + 1 . '天前';
    }else{
        return date('Y-m-d H:i:s',$time);
    }
}
Copy after login

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Composer cannot install laravel
From 1970-01-01 08:00:00
0
0
0
Laravel Space/laravel-backup cannot be installed
From 1970-01-01 08:00:00
0
0
0
Laravel 5.1 Login laravel comes with it No more
From 1970-01-01 08:00:00
0
0
0
Why thinkphp has better performance than laravel?
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template