Custom Date/Time formats in Ruby (on Rails)
In Switzerland we use a different formatting for date/time than in the USA (in fact most of Europe uses different formatting than the USA). Ruby (on Rails) is very centred on US coders and US applications and this can sometimes be a source of confusion and frustration. So let’s add some custom formats to Rails so we can not only to Date.today.to_s(:short) but also Date.today.to_s(:my_custom_date_format)
Rails has a built in set of formats which is stored in ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS and ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS and all you have to do is to add your own formats to this hash.
In config/initializers create a file date_formats.rb. This file we can use to register custom formats withouth messing up our environment.rb. If you need this often you could also extract it to a plugin so you can “install” your custom dateformats everywhere with a single script/install. In this file you can now merge your own formats to the existing ones or change existing formats:
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(:my_format => ‘%d. %m. %Y’)
The expressions you can use for formatting can be found in the source of Date.strftime. Or with this little piece of code:
>> (’a’..’z').each do |c|
?> expression = “%#{c}”
>> puts “#{expression} -> #{Date.today.strftime(expression)} / #{expression.upcase} -> #{Date.today.strftime(expression.upcase)}”
>> end
%a -> Sun / %A -> Sunday
%b -> Apr / %B -> April
%c -> Sun Apr 13 00:00:00 2008 / %C -> 20
%d -> 13 / %D -> 04/13/08
%e -> 13 / %E -> E
%f -> f / %F -> 2008-04-13
%g -> 08 / %G -> 2008
%h -> Apr / %H -> 00
%i -> i / %I -> 12
%j -> 104 / %J -> J
%k -> 0 / %K -> K
%l -> 12 / %L -> L
%m -> 04 / %M -> 00
%n ->
/ %N -> N
%o -> o / %O -> O
%p -> AM / %P -> am
%q -> q / %Q -> Q
%r -> 12:00:00 AM / %R -> 00:00
%s -> 1208044800 / %S -> 00
%t -> / %T -> 00:00:00
%u -> 7 / %U -> 15
%v -> 13-Apr-2008 / %V -> 15
%w -> 0 / %W -> 14
%x -> 04/13/08 / %X -> 00:00:00
%y -> 08 / %Y -> 2008
%z -> +0000 / %Z -> Z
=> “a”..”z”
For those who need even more you can register a Proc which will be called with the Date/Time to format as an argument:
>> proc = lambda do |what|
?> what.day - 1
>> end
Don’t forget to register your custom formats with Date and Time if you deal with Date and Time formatting!
back
November 30th, 2008 at 6:39
Hi there I like your post “Custom Date/Time formats in Ruby (on Rails)” so well that I like to ask you whether I should translate into German and linking back. Greetings Engel
December 4th, 2008 at 11:18
Hey Engel, sure, go right ahead. Post the link to it here as well, please.