Laravel time display problem, I want to let the time show:
For example: the publication time of an article:
**距离现在时间** **显示格式**< 1小时 xx分钟前1小时-24小时 xx小时前 1天-10天 xx天前>10天 直接显示日期
What should we do?
Reply content:
Laravel time display problem, I want to let the time show:
For example: the publication time of an article:
**距离现在时间** **显示格式**< 1小时 xx分钟前1小时-24小时 xx小时前 1天-10天 xx天前>10天 直接显示日期
What should we do?
Laravel itself has the perfect support for Carbon, ingenious use can achieve very good results:
First of all:
app/Providers/AppServiceProvider.phpAdd \Carbon\Carbon::setLocale('zh'); This line to your boot() method, (for cultural display)
public function boot() { \Carbon\Carbon::setLocale('zh'); }
Second:
ArticleAdd the Model following method to the:
public function getCreatedAtAttribute($date) { if (Carbon::now() < Carbon::parse($date)->addDays(10)) { return Carbon::parse($date); } return Carbon::parse($date)->diffForHumans(); }
Note here that the Laravel feature is used, and getXXXAttribute() if you are other fields, for example published_at , the method should be written getPublishedAtAttribute($date) , and don't forget to article the head use Carbon\Carbon; .
At last:
Just show your date right:
$article = \App\Article::find(7);{{ $article->created_at }}; // 视图中直接显示
More Laravel discussion study, please go to my station: https://laravist.com
Pro-Test: Laravel 5.1 and 5.2 are OK
Time issues front-end processing may be less stressful for the server, there is a moment.js you can try it.
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); }}