9

The default date format in Ruby is yyyy-mm-dd, but I needed them to be dd/mm/yyyy in the view

I have wrote a date_format file in config/initializers as:

Time::DATE_FORMATS.merge!( :uk_format => '%m/%d/%Y')

This didn't work since I need to call date.to_s(:uk_format) in order to use this format. But since I'm using <%= f.text_field :paymentDate %> to display the date, I'm not sure I can add to_s to this case.

Can someone help me out please.


Edit 1

Actually date.to_s(:uk_format) doesn't work either, how do I use initializer properly.....?

Souloikj
  • 360
  • 2
  • 9
  • 19

2 Answers2

27

See: Change default Ruby Time format

Adapted my answer linked to above for the Date and format specified:


Since you're using Rails, take advantage of the I18n support: http://guides.rubyonrails.org/i18n.html#adding-date-time-formats

# config/locales/en.yml
en:
  date:
    formats:
      default: "%d/%m/%Y"

Then you can call I18n.l Date.today to get out a formatted date. Or in your view, you can use <%= l @foo.created_at %>.

Community
  • 1
  • 1
coreyward
  • 77,547
  • 20
  • 137
  • 166
  • 3
    What about calling date from database, does this gets effected as well? – Souloikj Mar 14 '11 at 19:51
  • As an output helper, I18n will work on whatever data you give it, regardless the source, so yes, it works fine for displaying dates from the database. It's a really bad idea to transform dates into display format for storage, though, if that's what you mean. – coreyward Apr 28 '12 at 21:18
  • What about getting that default date format reflected in form fields (e.g. when editing a date attribute on a model)? – findchris Feb 02 '13 at 16:10
  • @findchris That's a totally separate question, and I bet it's been answered on here before, but if you can't find it, ask it. ;) – coreyward Feb 02 '13 at 19:33
  • 1
    As for me, Rails 3.2.13 and created_at, I had to use en: time: ... instead of en: date: – krzemian Jun 17 '13 at 02:06
2

Try this instead:

Time::DATE_FORMATS.merge!({:db => '%m/%d/%Y', :uk_format => '%m/%d/%Y'})
Date::DATE_FORMATS.merge!({:db => '%m/%d/%Y', :uk_format => '%m/%d/%Y'})
Artem Kalinchuk
  • 6,502
  • 7
  • 43
  • 57