Translating dates in ruby (on rails)

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"

Advertisement

8 thoughts on “Translating dates in ruby (on rails)

  1. 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)

  2. 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

  3. I have the same problem! My calendar uses Date::DAYNAMES to get the days of the week. And now I can’t translate them! How to do?

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s