Custom Date And Time Formats In Rails

Dan Croak

We wanted to shorten “about 1 month ago” text in an information-rich table.

wrapping onto multiple lines

We can override distance_in_words with the i18n API (and, by extension, time_ago_in_words).

Speaks English real good

A quick change to config/locales/en.yml and we’re done:

en:
  datetime:
    distance_in_words:
      less_than_x_seconds:
        other: '1 minute'
      half_a_minute: '1 minute'
      less_than_x_minutes:
        one: '1 minute'
      x_minutes:
        one: '1 minute'
        other: '{{count}} minutes'
      about_x_hours:
        one: '1 hour'
        other: '{{count}} hours'
      about_x_months:
        one: '1 month'
        other: '{{count}} months'
      about_x_years:
        one: '1 year'
        other: '{{count}} years'
      over_x_years:
        one: 'over 1 year'
        other: 'over {{count}} years'

The result:

fits on one line

You can see other options in svenfuchs/i18n.