Time format

I found an interesting article by Todd Sayre on time formats in Rails. It is only short, but interesting. Based on that I created config/initializers/time_formats.rb in my latest app:

# Used to create time and datetime formatting short cuts. Search for to_formatted_s in the api
# Also see http://snippets.dzone.com/posts/show/2406

# If date = Time.local(2009,12,24,15,30,27)

Time::DATE_FORMATS[:datetime] = "%d-%b-%Y %H:%M"  # date.to_s(:datetime)  ---->  24-Dec-2009 15:30
Time::DATE_FORMATS[:date] = "%d-%b-%Y"            # date.to_s(:date)      ---->  24-Dec-2009
Time::DATE_FORMATS[:time] = "%H:%M"               # date.to_s(:time)      ---->  15:30
Time::DATE_FORMATS[:default] = Time::DATE_FORMATS[:datetime]   # Sets default behaviour for date.to_s

I think the code speaks for itself. As you can see it is very easy to extend Time#to_s to provide straight forward formatting. It is also easy to overwrite the default

Update

Note that the previous format only affected Time objects. Date object text formats have to be defined separately. However, if you want the two to share a common format, this is a useful technique:

date_formats = {
  concise: '%d-%b-%Y' # 13-Jan-2014
}

Time::DATE_FORMATS.merge! date_formats
Date::DATE_FORMATS.merge! date_formats
This entry was posted in Ruby. Bookmark the permalink.