Organizing custom Date(Time) formats

Updated . Posted . Visible to the public.

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 instead. You can add localizations for your custom formats the same way you add them for existing formats.

Niklas Hä.
Last edit
Jonas Schiele
License
Source code in this card is licensed under the MIT License.
Posted by Niklas Hä. to makandra dev (2022-11-08 08:52)