如何在 laravel 4 中发布(时间)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17076823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a posted at (time), in laravel 4
提问by Chachoo Aguirre
I'm making my web site in Laravel 4 and I have the created_at
& updated_at
fields in the table. I want to make a news system that gives me how much time has passed since the post has been made.
我正在 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 |
I want to show something like:
我想展示类似的东西:
-created 5 minutes ago
-created 5 months ago
-创建于 5 分钟前
-创建于 5 个月前
if the post is older than 1 month
如果帖子超过 1 个月
-created at Nov 5 2012
-创建于 2012 年 11 月 5 日
回答by rmobis
Try using Carbon. Laravel already comes with it as a dependency, so there is no need to add it yours.
尝试使用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();
}
As requested, I'll give an example of full integration, on how I think would be the better way to do it. First, I assume I might use this on several different places, several different views, so the best would be to have that code inside your model, so that you can conveniently call it from anywhere, without any hassle.
根据要求,我将举一个完全集成的例子,说明我认为如何更好地做到这一点。首先,我假设我可能会在几个不同的地方、几个不同的视图中使用它,所以最好将这些代码放在你的模型中,这样你就可以从任何地方方便地调用它,没有任何麻烦。
Post.php
后.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();
}
}
}
Then, in your view files, you'd simply do $news->formattedCreatedDate()
. Example:
然后,在您的视图文件中,您只需执行$news->formattedCreatedDate()
. 例子:
<div class="post">
<h1 class="title">{{ $news->title }}</h1>
<span class="date">{{ $news->forammatedCreatedDate() }}</span>
<p class="content">{{ $news->content }}</p>
</div>
回答by Antonio Carlos Ribeiro
Require Carbon:
需要碳:
use Carbon\Carbon;
And use it:
并使用它:
$user = User::find(2);
echo $user->created_at->diffForHumans( Carbon::now() );
You should get this:
你应该得到这个:
19 days before