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
The usage is quite simple. Instead of
You can do instead:
I18n.l Time.now, format: :myformat
myformat format defined in a locale file, say
en: time: formats: myformat: '%Y-%m-%d %H:%M;%s'
The format string supports all the same format options as
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
I18n.lhas 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'
myformat is not such a great name for a format name ;). In a real
application I would use something like
A couple of formats,
: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.