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

标签 php datetime laravel laravel-4

我在 Laravel 4 中制作我的网站,我在表中有 created_atupdated_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/

相关文章:

c# - DocumentDB如何对_TS进行LINQ查询?

laravel - 在 laravel fortify 中启用记住我选项

php - Paypal api成功或失败

javascript - 如何将 php 文件中的值包含到 jQuery 中并将其放入 span 元素中?

带有日期的 php fatal error

ruby-on-rails - 在 Rails 中设置标准日期/时间格式

jquery - 如何在 Laravel 中通过 Ajax 提交表单

mysql - 在后端阻止连续的 SQL 请求

php - 检查选择中的总和值

php - 通过 PHP 传输链接数据?