Rails Date Formats

First published on Fencore Ltd.’s Posterous page on December 3rd, 2010

(Note that the comment about working in Britain is no longer true, as I now reside in the USA.)

I don’t know about you but I get confused when working with dates as the built-in formats don’t work for me.
Ruby has a Date library that implements both the Date and DateTime classes and Rails extends these in its ActiveSupport library. There is also a Time class and, of course, these things cannot exist in isolation from each other.
As I work in Britain, I need to be able to produce dates in British format. I add custom formats to the Rails DATE_FORMATS hash by creating a file in config/initializers with the following contents:

Date::DATE_FORMATS[:british] = "%d/%m/%Y"
Date::DATE_FORMATS[:british_long] = "%d %B, %Y"
Date::DATE_FORMATS[:british_long_ordinal] = lambda { |date|
date.strftime("#{ActiveSupport::Inflector.ordinalize(date.day)} %B, %Y") } # => "25th April, 2007"

According to the documentation (for Rails 3.0.3 look at the ActiveSupport RDocs and then for to_formatted_s(format = :default) in DateTime), the file should be called config/initializers/time_formats.rb but it turns out that is is more of a suggestion than a ‘must do’. I found this out when I called I called it date_formats.rb by mistake; in fact I tried calling it splat.rb and it still worked, so perhaps something a little more generic like date_time_formats.rb would be better.
With that in place, and noting that to_formatted_s is aliased to to_s, you can do things like:

> date = Date.today => Fri, 03 Dec 2010
> date.to_s # this is the default output
=> "2010-12-03"
> date.to_s(:long) # this is pre-defined
=> "December 3, 2010"
> date.to_s(:british)
=> "03/12/2010"
> date.to_s(:british_long)
=> "03 December, 2010"
> date.to_s(:british_long_ordinal)
=> "3rd December, 2010"

You can do a similar thing with times (although I find no need to) and of course, you can define your own formats to satisfy your own local needs.
What about converting from a string to a Date or DateTime object?
Well, the strptime method is part of the Ruby language, so the following works:

> Date.strptime("31/01/2010", "%d/%m/%Y")
=> Sun, 31 Jan 2010 DateTime.strptime("31/01/2010", "%d/%m/%Y")
=> Sun, 31 Jan 2010 00:00:00 +0000

Note that I am using Ruby 1.9.2, although I believe nothing has changed from 1.8.x


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s