Custom Date And Time Formats In Rails

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.

Pair with one of our expert developers to level up your skills with Coaching by thoughtbot. Save time learning best practices and techniques for reducing technical debt in Ember, Ruby, Haskell, and Go in 1-on-1 sessions tailored to your goals.