【问题标题】:Changing date-time to Month, Day, Year将日期时间更改为月、日、年
【发布时间】:2014-01-16 13:20:55
【问题描述】:

我正在我当前的 Rails 网站上集成一个新的引导模板。我正在写我的博客,现在我的帖子显示为"10 minutes ago"。我想更改日期格式,例如Dec, 21, 2012 in separate lines

新模板只需硬编码日期即可:

  <div class="blog-date">
    <span class="blog-date-month">Dec</span>
    <span class="blog-date-day">21</span>
    <span class="blog-date-year">2012</span>
  </div>

我得到日期的方法是使用这个:

time_ago_in_words(post.created_at)

我的问题是如何提取帖子的创建日期,以月、年和日等单独的元素?

【问题讨论】:

    标签: ruby-on-rails datetime ruby-on-rails-4


    【解决方案1】:

    time_ago_in_words 会将 Time 对象转换为人类可表示且易于阅读的字符串。

    在您的情况下,您不需要它。您可以简单地使用post.created_at 上的日期/时间方法来获取年、月和日:

    • post.created_at.year
    • post.created_at.mday
    • post.created_at.month

    请注意,这些将以数字形式返回结果(例如 12 而不是 12 月)。您可以使用I18n utils 来取回缩写名称,如下所示:

    • I18n.t("date.abbr_month_names")[post.created_at.month]

    您也可以使用strftime 将时间转换为字符串:

    • post.created_at.strftime('%b')

    但是请注意,如果您关心国际化,这将不会通过 Rails 的 I18n 引擎。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      相关资源
      最近更新 更多