Date format in rails

1

I currently have this format for my date %B %d, %Y which returns martes mayo 15, 2018 but I would like to modify it so that I will return this format Tuesday, August 26 and that in turn will work with i18n.

I currently have this: %A %d de %B but I need to work with other i18n.

    
asked by mariovzc 16.05.2018 в 19:27
source

1 answer

2

To work with other languages in I18n , you need to create the corresponding locale files; for example, this would be for Spanish:

# config/locales/es.yml

es:
  date:
    formats:
      default: "%A %d de %B"
    month_names: [~, Enero, Febrero, Marzo, Abril, Mayo, Junio, Julio, Agosto, Septiembre, Octubre, Noviembre, Diciembre]
    abbr_month_names: [~, Ene, Feb, Mar, Abr, May, Jun, Jul, Ago, Sep, Oct, Nov, Dic]
    day_names: [Domingo, Lunes, Martes, Miércoles, Jueves, Viernes, Sábado]

And you would use it with the I18n.l method; example in console and default locale in English:

fecha = Date.new(2018,5,15)
#=> Tue, 15 May 2018

I18n.l(fecha, locale: :es)
#=> "Martes 15 de Mayo"

If you want to add more, simply add a new key in formats ; for example:

# config/locales/es.yml

es:
  date:
    formats:
      default: "%Y-%m-%d"
      long: "%A %d de %B"
    month_names: [~, Enero, Febrero, Marzo, Abril, Mayo, Junio, Julio, Agosto, Septiembre, Octubre, Noviembre, Diciembre]
    abbr_month_names: [~, Ene, Feb, Mar, Abr, May, Jun, Jul, Ago, Sep, Oct, Nov, Dic]
    day_names: [Domingo, Lunes, Martes, Miércoles, Jueves, Viernes, Sábado]

And to use it you must indicate indicate the format:

fecha = Date.new(2018,5,15)
#=> Tue, 15 May 2018

I18n.l(fecha, locale: :es)
#=> "2018-05-15"

I18n.l(fecha, locale: :es, format: :long)
#=> "Martes 15 de Mayo"

In the view you can use only l (without the need to indicate locale ):

<%= l @fecha %>
<%= l @fecha, format: :long %>

To add more locales (languages), you must generate new files with the translations of each language specifying the translation for the date format you need ( long in the last example). p>

For example, if you wanted to add Italian, you could generate the following file in config / locales / :

# config/locales/it.yml

it:
  date:
    formats:
      default: "%Y-%m-%d"
      long: "%A %d %B"
    month_names: [~, Gennaio, Febbraio, Marzo, Aprile, Maggio, Giugno, Luglio, Agosto, Settembre, Ottobre, Novembre, Dicembre]
    abbr_month_names: [~, Gen, Feb, Mar, Apr, Mag, Giu, Lug, Ago, Set, Ott, Nov, Dic]
    day_names: [Domenica, Lunedì, Martedì, Mercoledì, Giovedì, Venerdì, Sabato]

And to use it:

fecha = Date.new(2018,5,15)
#=> "2018-05-15"

I18n.l(fecha, locale: :it, format: :long)
#=> "Martedì 15 Maggio"
    
answered by 16.05.2018 / 20:19
source