views:

46

answers:

3

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 does 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?

+4  A: 

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

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

Geoff Lanotte
+1 For the resources - Thanks!
Jamie Wong
+2  A: 

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

Jamie Wong
A: 

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.

Michal