开发者

Follow up to changing Date format from Time.now to post.created_at

I previously asked a question on stack overflow about how to format my date in a readable manner. This was the gist of it was this.

How do I take

2010-06-14 19:01:00 UTC

and turn it into

June 14th, 2010

The answer that I used was calling post.date and simply adding the below to post.rb

@date = Time.now
@date.strftime("%B %d, %Y")

It doe开发者_如何学JAVAs show the date in words but I don't want to show the current date. I want the post.created_at date.

How can I modify the above (or what do I need to add elsewhere) to get this to work?


post.created_at.strftime("%B %d, %Y")

A good resource for strftime is http://strfti.me


You can define your own formatters for reuse as initializers.

 # config/initializers/time_formats.rb
  Time::DATE_FORMATS[:nice] = "%B %d, %Y"

Then use

 User.created_at.to_formatted_s(:nice)

Reference

  • http://apidock.com/rails/ActiveSupport/CoreExtensions/DateTime/Conversions/to_formatted_s


If you're using Rails you can also define custom time formats in locales.

That's what I have for Polish locale:

pl:
  date:
    formats:
      default: "%Y-%m-%d"
      short: "%d %b"
      long: "%d %B %Y"

    day_names: [Niedziela, Poniedziałek, Wtorek, Środa, Czwartek, Piątek, Sobota]
    abbr_day_names: [nie, pon, wto, śro, czw, pia, sob]

    month_names: [~, Styczeń, Luty, Marzec, Kwiecień, Maj, Czerwiec, Lipiec, Sierpień, Wrzesień, Październik, Listopad, Grudzień]
    abbr_month_names: [~, sty, lut, mar, kwi, maj, cze, lip, sie, wrz, paź, lis, gru]
    order: [ :year, :month, :day ]

  time:
    formats:
      default: "%a, %d %b %Y, %H:%M:%S %z"
      short: "%d %b, %H:%M"
      long: "%d %B %Y, %H:%M"
    am: "przed południem"
    pm: "po południu"

Then in views you localize timestamps with:

<%= l(@post.created_at, :format => :long) %>

Or outside views:

I18n.l(@post.created_at, :format => :long)

That's more flexible than defining formats directly in Time or Date classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜