– we create awesome web applications

Stop using strftime. Seriously. At least if you are using Rails that is.

Rails, or rather, its I18N dependency, has a much better alternative I18n.l. The great thing about it is that you provide the name/kind of the format that you want separately of the format itself, so that you can, for example, change it completely for the whole application, or for a different locale.

The usage is quite simple. Instead of

Time.now.strftime('%Y-%m-%d %H:%M:%S')

You can do instead:

I18n.l Time.now, format: :myformat

with the myformat format defined in a locale file, say config/locale/time_formats.en.yml:

en:
  time:
    formats:
      myformat: '%Y-%m-%d %H:%M;%s'

The format string supports all the same format options as strftime, so conversion of your existing strftime code should be completely trivial.

It is important to pass a Symbol to the :format option of I18n.l, or it will try to interpret it as the format itself, and not its 'name' in the localization file.

Note: I18n.l has an alias I18n.localize, feel free to use it if you like to type.

When you are inside of a Rails view, you have another shortcut:

= l Time.now, format: :myformat

This is not all, yet...

It works for dates to:

I18n.l Date.today, format: :myformat

Event though it uses the same format name, it will use a different localisation key:

en:
  date:
    formats:
      myformat: '%Y-%m-%d'

Of course myformat is not such a great name for a format name ;). In a real application I would use something like compact, full, connfig, etc.

A couple of formats,:short, and :long are already provided, but I wouldn't rely on them and I suggest you define by yourself any time/date format that you intend to use inside of your application.

comments powered by Disqus