我在 Laravel 4 中制作我的网站,我在表中有 created_at
和 updated_at
字段。我想制作一个新闻系统,告诉我自发布帖子以来已经过去了多少时间。
| name | text | created_at | updated_at |
| __________ | __________ | ________________________ | ___________________ |
| news name | news_text | 2013-06-12 11:53:25 | 2013-06-12 11:53:25 |
我想展示类似的东西:
-created 5 minutes ago
-created 5 months ago
如果帖子超过 1 个月
-created at Nov 5 2012
最佳答案
尝试使用 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();
}
根据要求,我将给出一个完全集成的示例,说明我认为如何做是更好的方法。首先,我假设我可能会在几个不同的地方、几个不同的 View 中使用它,所以最好是将该代码放在您的模型中,这样您就可以从任何地方方便地调用它,没有任何麻烦。
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();
}
}
}
然后,在您的 View 文件中,您只需执行 $news->formattedCreatedDate()
。示例:
<div class="post">
<h1 class="title">{{ $news->title }}</h1>
<span class="date">{{ $news->forammatedCreatedDate() }}</span>
<p class="content">{{ $news->content }}</p>
</div>
关于php - 如何在(时间),在 laravel 4 中发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17076823/