24

I am finding myself repeating typing many strftime which I defined.

Having watch Ryan Bates's railscasts ep 32/33( I think), I created a custom option for the to_s method as in Time.now.to_s, so that I can do Time.now.to_s(:sw), where :sw is my custom method, to retrieve "23 Sep 2010, 5:00PM" for example.

But the problem is, I don't know where to put #sw's definition. Should it be in a file in in the initializer folder? Or should it go in application.rb?

Thanks!

Nik So
  • 16,683
  • 21
  • 74
  • 108

4 Answers4

45

Use "time" instead of "date" in your locales file, since Rails timestamps are datetimes.

in config/locales/en.yml

en:
  time:
    formats:
      default: "%Y/%m/%d"
      short: "%b %d"
      long: "%B %d, %Y"

in app/views/posts/show.html.haml

  = l post.updated_at
  = l post.created_at, :format => :long
tee
  • 4,149
  • 1
  • 32
  • 44
22

I have a file config/initialisers/time_formats.rb containing:

...
Time::DATE_FORMATS[:posts] = "%B %d, %Y"
Time::DATE_FORMATS[:published] = "%B %Y"
...

You just need to restart your server to have the changes picked up.

Dorian
  • 22,759
  • 8
  • 120
  • 116
Hugo
  • 2,913
  • 1
  • 20
  • 21
  • Okay, I thought so, too.Also because that way, you get to organize these 'helpers' in files rather than in lines in the application.rb Thanks! – Nik So Sep 07 '10 at 00:27
5

Use Rails I18n API.

# config/locales/en.yml
en:
  date:
    formats:
      default: "%Y-%m-%d"
      short: "%b %d"
      long: "%B %d, %Y"

# in views 
= l post.updated_at # will use default format of date in locales yml file

see about I18n API

Jeremy Mack
  • 4,987
  • 2
  • 25
  • 22
cactis
  • 205
  • 5
  • 5
0

Please read this post:

Rails - to_formatted_s

Create file with name: config/initializers/time_formats.rb

Time::DATE_FORMATS[:my_custom_time_format] = "%Y-%m-%d %H:%M"

And you can use:

formated_date = my_date.to_formatted_s(:my_custom_time_format)

Note: You must to restart your rails server (WEBRick, FCGI, etc)

d.danailov
  • 9,594
  • 4
  • 51
  • 36
  • Ah, I was pulling my hair out trying to figure out why my formats were not changing. Thanks for the server restart tip! – AndrewJM Jun 05 '14 at 20:42