Organizing custom Date(Time) formats

Large Rails projects tend to define multiple custom ways to format Dates or DateTimes. This often leads to duplicated format strings, wrong formats and unnecessary introduction of new formats.

to_fs also supports to refer to those formats by name e.g. to_formatted_s(:iso_8601) or to_formatted_s(:short).
to_fs is an alias for to_formatted_s.

Those names are defined in Time::DATE_FORMATS and it's possible to add your own formats. There is a how to in the official docs Show archive.org snapshot .

One example:

DateTime.now.to_fs('%d/%Y')

Time::DATE_FORMATS[:custom] = '%d/%Y'

DateTime.now.to_fs(:custom)

A similar format hash exists for Date. Date::DATE_FORMATS can be modified to add custom date formats.

Note

Don't use this to localize your formats. For this use I18n.l Show archive.org snapshot instead. You can add localizations for your custom formats the same way you add them for existing formats.

Niklas Hä. Over 1 year ago