Read more

Organizing custom Date(Time) formats

Niklas Hä.
November 08, 2022Software engineer at makandra GmbH

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.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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.

Posted by Niklas Hä. to makandra dev (2022-11-08 09:52)