Skip to content

Instantly share code, notes, and snippets.

@mudge
Last active September 5, 2023 09:32
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mudge/5152839 to your computer and use it in GitHub Desktop.
Save mudge/5152839 to your computer and use it in GitHub Desktop.
Using date ordinals in Rails through an I18n time format.
# This goes in config/locales/en.rb (*not* en.yml)
{
:en => {
:time => {
:formats => {
:full => lambda { |time, _| "%H:%M | %A, #{time.day.ordinalize} %B %Y" }
}
}
}
}
<%= l(Time.now, :format => :full) %>
<!-- 14:50 | Wednesday, 13th March 2013 -->
@jhubert
Copy link

jhubert commented Feb 16, 2016

This is awesome. Thank you.

@mikeahmarani
Copy link

Agreed. Thanks!

@SirRawlins
Copy link

This is nice, hadn't ever considered using .rb files for dynamic locale stuff like this. I've just thrown together a quick drop-in patch which updates the :default, :short and :long options for both dates and times.

{
  :en => {
    :date => {
      :formats => {
        :short => lambda { |date, _| "%b #{date.day.ordinalize}" },
        :long => lambda { |date, _| "%B #{date.day.ordinalize}, %Y" }
      }
    },
    :time => {
      :formats => {
        :default => lambda { |time, _| "%a, #{time.day.ordinalize} %b %Y %H:%M:%S %z" },
        :short =>  lambda { |time, _| "#{time.day.ordinalize} %b %H:%M" },
        :long =>  lambda { |time, _| "%B #{time.day.ordinalize}, %Y %H:%M" }
      }
    }
  }
}

Could no doubt be DRYed up a bit but works all the same.

@danielricecodes
Copy link

Wow. I've been working with Rails since version 1 and I am still learning new tricks.

@hoffmanc
Copy link

hoffmanc commented Mar 7, 2019

since 0.13 here and I agree 👍

@letmein
Copy link

letmein commented Jun 3, 2021

Thanks for sharing it 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment