Friday, 11 April 2008

Rake quick tip - Getting your dates out into the right format

Rails date formatting leaves a bit to be desired with only a few formats available. You can of course use strftime in all it's glory:

but it is hardly descriptive.

So there are a couple of ways of getting dates to format as you want them in Rails. The first is to set your own key in the date format table, and select it explicitly.
Time::DATE_FORMATS[:uk] = "%d-%b-%y"

But if you want this date format all the time, just overwrite the :default key. Then to_s will use your format by default.
Time::DATE_FORMATS[:default] = "%d-%b-%y"

I stick the command in the ApplicationHelper. It's always a global change.