如何在(时间)发布,在laravel 4

Cha*_*rre 3 php datetime laravel laravel-4

我正在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 |
Run Code Online (Sandbox Code Playgroud)

我想表现出类似的东西:

- 5分钟前创建

- 5个月前创建

如果帖子超过1个月

- 创建于2012年11月5日

rmo*_*bis 11

尝试使用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();
}
Run Code Online (Sandbox Code Playgroud)

根据要求,我将举一个完全整合的例子,我认为这是更好的方法.首先,我假设我可以在几个不同的地方,几个不同的视图中使用它,所以最好的方法是在模型中包含该代码,以便您可以方便地从任何地方调用它,而不会有任何麻烦.

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();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

然后,在您的视图文件中,您只需执行此操作$news->formattedCreatedDate().例:

<div class="post">
    <h1 class="title">{{ $news->title }}</h1>
    <span class="date">{{ $news->forammatedCreatedDate() }}</span>
    <p class="content">{{ $news->content }}</p>
</div>
Run Code Online (Sandbox Code Playgroud)