ruby-on-railsrails-i18n

Displaying the date pattern string in Rails i18n localization


I'd like to get the template string of the localized date format in Rails. What I'm going for:

date_in_us = get_date_string(:en) # 'mm/dd/yyyy'
date_in_gb = get_date_string(:en-gb) # 'dd/mm/yyyy'

So to be clear I'm not trying to localize a real date, I'm trying to get the date format string so I could display it as a placeholder in a text field.

Everything I've searched for on the internet keeps bringing me back to actually localizing a date. :-/


Solution

  • That won't work because that's not how the format is specified. For English, this is how the date formats are specified:

    formats:
      default: "%Y-%m-%d"
      long: "%B %d, %Y"
      short: "%b %d"
    

    Here are the docs for these percent placeholders in case you're curious.

    To solve your problem, I'd create a date, localize it, and replace the parts:

    date = Date.new(2000, 12, 31)
    I18n.l(date).sub('2000', 'yyyy').sub('12', 'mm').sub('31', 'dd')
    # => "yyyy-mm-dd"
    

    Note that this might not work if the locale uses a 2 digit year format. Let's try it for some locales (using the default from rails-i18n):

    def get_date_string(locale = I18n.current)
      date = Date.new(2000, 12, 31)
      I18n.l(date, locale: locale)
        .sub('2000', 'yyyy')
        .sub('12', 'mm')
        .sub('31', 'dd')
    end
    
    formats = %i[en en-US en-GB es de fr pt].map do |locale|
      [locale, get_date_string(locale)]
    end.to_h
    

    formats will be:

    {
      :en=>"yyyy-mm-dd",
      :"en-US"=>"mm-dd-yyyy",
      :"en-GB"=>"dd-mm-yyyy",
      :es=>"dd/mm/yyyy",
      :de=>"dd.mm.yyyy",
      :fr=>"dd/mm/yyyy",
      :pt=>"dd/mm/yyyy"
    }