尝试使用碳。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>