Question

I'm having an issue which I can't seem to figure out. I'm trying to format a date using a custom format I've defined in my en.yml file:

en:
  hello: "Hello world"
  time:
      formats:
          history_table: "%m/%d/%Y %I:%M:%S %p %Z"

This is being called using the 'l' helper:

l version.created_at, :format => :history_table

For some reason this is displaying the AM/PM in lowercase, instead of in uppercase as should be the case with %p.

I've played around in the console a bit, and it seems like it's a difference in behavior between the localization function and strftime:

ruby-1.9.2-p180 :043 > I18n.l user.updated_at, :format => "%m/%d/%Y %I:%M:%S %p %Z"
 => "03/23/2011 01:52:16 am UTC" 
ruby-1.9.2-p180 :044 > user.updated_at.strftime("%m/%d/%Y %I:%M:%S %p %Z")
 => "03/23/2011 01:52:16 AM UTC"

Am I doing something wrong? Is this a bug? Any guidance is greatly appreciated as my forehead is sore from banging it against the wall.

Edit: This has been solved(ish). Looking at the default activesupport localization, there isn't any differentiation between %p and %P. https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml

I over-rode the localization in my local en.yml file to use uppercase. I would really have liked to see Rails support both options however.

Was it helpful?

Solution

Looking in the source for active support, I found the following under english localization:

  time:
    formats:
      default: "%a, %d %b %Y %H:%M:%S %z"
      short: "%d %b %H:%M"
      long: "%B %d, %Y %H:%M"
    am: "am"
    pm: "pm"

In other words, there is no distinction between %P and %p built-in to localization as there is in strftime. This unfortunately means that in individual custom formats it is not possible to choose between upper and lower case representations, but it is possible to define which you would like globally by over-riding the default formats in your own en.yml file. For example, here's my updated en.yml file that now causes the output of upper-case AM/PM.

en:
  hello: "Hello world"
  time:
      formats:
          history_table: "%m/%d/%Y %I:%M:%S %p %Z"
      am: "AM"
      pm: "PM"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top