嘗試使用Carbon。 Laravel已經將它作爲依賴項,所以不需要添加它。
use Carbon\Carbon;
// ...
// If more than a month has passed, use the formatted date string
if ($new->created_at->diffInDays() > 30) {
$timestamp = 'Created at ' . $new->created_at->toFormattedDateString();
// Else get the difference for humans
} else {
$timestamp = 'Created ' $new->created_at->diffForHumans();
}
按照要求,我會充分整合,對我怎麼覺得這是更好的方式來做到這一點的例子。首先,我假設我可能會在幾個不同的地方和幾種不同的視圖中使用它,所以最好的做法是將這些代碼放入模型中,以便您可以方便地從任何地方調用它,而不會有任何麻煩。
post.php中
class News extends Eloquent {
public $timestamps = true;
// ...
public function formattedCreatedDate() {
ìf ($this->created_at->diffInDays() > 30) {
return 'Created at ' . $this->created_at->toFormattedDateString();
} else {
return 'Created ' . $this->created_at->diffForHumans();
}
}
}
然後,在視圖文件,你根本就$news->formattedCreatedDate()
。例如:
<div class="post">
<h1 class="title">{{ $news->title }}</h1>
<span class="date">{{ $news->forammatedCreatedDate() }}</span>
<p class="content">{{ $news->content }}</p>
</div>
酷的故事。到目前爲止你做了什麼? – Jessica