Search code examples
ruby-on-railsrails-i18ni18n-gem

Rails translate current date in another format


In Rails I'm trying to localize the date:

2.1.1 :005 > Date.today
 => Mon, 14 Apr 2014 
2.1.1 :006 > I18n.localize(Date.today)
 => "14/04/2014" 
2.1.1 :007 > 

The second output is not the correct translation of the first!

Can you help me ?


Solution

  • You can define a new format:

    en:
      date: # there is also a section for datetime and time
        formats:
          day_month_abbr: "%a, %d %b %Y"
    

    and use it like this:

    I18n.localize(Date.today, format: :day_month_abbr)
    # => "Mon, 14 Apr 2014"
    

    Or you can overwrite the default format:

    en:
      date:
        formats:
          default: "%a, %d %b %Y"
    

    And then you don't need to give any argument:

    I18n.l(Date.today) #=> "Mon, 14 Apr 2014"
    

    List of all the wildcards usable for DateTime/Time/Date here: http://apidock.com/ruby/DateTime/strftime