The Laravel time display problem occurs. I want to display the time in this way: for example, the posting time of an article: {code...} How should I do it? Laravel time display problem. I want to display the time as follows:
For example, when an article is published:
** Display format ** <1 hour xx minutes ago 1 hour-24 hours xx hours ago 1 day-10 days xx days ago> 10 days direct display date
What should I do?
Reply content:
Laravel time display problem. I want to display the time as follows:
For example, when an article is published:
** Display format ** <1 hour xx minutes ago 1 hour-24 hours xx hours ago 1 day-10 days xx days ago> 10 days direct display date
What should I do?
Laravel has the perfect support for Carbon, and the clever use can achieve good results:
First:
In yourapp/Providers/AppServiceProvider.php
Add\Carbon\Carbon::setLocale('zh');
This lineboot()
Method (for cultural display)
public function boot() { \Carbon\Carbon::setLocale('zh'); }
Second:
InArticle
OfModel
Add the following method:
public function getCreatedAtAttribute($date) { if (Carbon::now() < Carbon::parse($date)->addDays(10)) { return Carbon::parse($date); } return Carbon::parse($date)->diffForHumans(); }
Note that Laravel'sgetXXXAttribute()
If you are using other fields, suchpublished_at
, The method should be writtengetPublishedAtAttribute($date)
Don't forget to go to the Article Headeruse Carbon\Carbon;
.
Finally:
Simply display your date:
$ Article = \ App \ Article: find (7) ;{{$ article-> created_at }}; // directly displayed in the view
For more information about Laravel, please visit my site: https://laravist.com
Test: Laravel 5.1 and 5.2 are both OK.
Front-End Processing of time problems may put less pressure on the server. you can have a try with moment. js.
Moment. js
Public function formatDate ($ time = 0) {$ tmp = time ()-$ time; if ($ tmp & $ tmp <= 60*60) {return ceil ($ tmp/60) + 1. 'minute ago ';} elseif ($ tmp> 60*60 & $ tmp <60*60*24) {return ceil ($ tmp/60/60) + 1. 'hour ago ';} elseif ($ tmp> 60*60*24 & $ tmp <60*60*24*10) {return ceil ($ tmp/60/60/24) + 1. 'Day before ';} else {return date ('Y-m-d H: I: s', $ time );}}