Tigraine

Daniel Hoelbling-Inzko talks about programming

Formatting Date and Times in Rails

When looking at formatting Times and Dates in a certain format one quickly looks at strftime for help. Only problem there is that strftime will not take into account the translations configured through Rails I18n gem. So a german representation of 10. Oct 2015 will not render correctly since October is abbreviated in german as Okt.

A solution would be to just define the format pattern through the I18n translations inside the yaml files in config/locales/ - but often you have formats that are set just this once, so externalizing them is not really a good solution.

Looking at the I18n gem the solution is quite easy: I18n.localize(<date>, format: '%d. %b %Y') yields the appropriate result while passing in the localization format. So just replacing the date.strftime(<pattern>) call with I18n.localize(date, format: <pattern>) is the way to go.

You can also pass in the locale you want it formatted in using the locale: :de parameter to localize.

Hope this helps.

Filed under rails3, rails, i18n

My Photography business

Projects

dynamic css for .NET

Archives

more