Translating dates in ruby (on rails)

Posted by Jorge Bernal January 17, 2007

Update: month names list has nil at the beginning

Based on Localization for Ruby’s Time#strftime, I’ve come across a simple solution when you are developing a non-multilanguage app in a non-English language.

If it’s for rails, we put this on lib/environment.rb. In any other cases, put this code at the initialisation stage

  Date::MONTHNAMES.replace [nil] + %w(Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre)
  Date::DAYNAMES.replace = %w(Domingo Lunes Martes Miércoles Jueves Viernes Sábado)
  Date::ABBR_MONTHNAMES.replace [nil] + %w(Ene Feb Mar Abr May Jun Jul Ago Sep Oct Nov Dic)
  Date::ABBR_DAYNAMES.replace %w(Dom Lun Mar Mié Jue Vie Sab)

Of course, you should translate it to your language if it’s not Spanish.

The result:

  >> Date.today.strftime("%A, %d de %B de %Y")
  => "Miércoles, 17 de Febrero de 2007"

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Furl
  • Google Bookmarks
  • email
  • StumbleUpon

Related posts

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

6 Responses to “Translating dates in ruby (on rails)”

  1. Jose says:

    I had a problem with this code “can’t modify frozen array (TypeError)” cant get it to work

  2. Frank Fischer says:

    This won’t work with Date::MONTHNAMES Array beeing frozen since Ruby 1.8.6

  3. blaxter says:

    for freezing constant you can redefine them (with a warning) with monkeypatching:


    class Date
    ABBR_DAYNAMES = %w(Dom Lun Mar Mié Jue Vie Sab)
    end

    or with const_set:


    Date.const_set 'ABBR_DAYNAMES', %w(Dom Lun Mar Mié Jue Vie Sab)

  4. Gazer says:

    In moderns rails (2.2+ I think) you can use the I18n API :

    I18n::localize(Date.today, :format => “%B %Y”)

  5. Nico says:

    it’s still a mess !!
    can’t find a way to get the translated day of the week !
    and if i get it from DATE::DAYNAMES , i get the english version.. that’s plain stupid

Leave a Reply