1
votes

I would like to store date for some data in Rails app. User can select a date, sometimes it would be specific (like "1 Jan 2010") but sometimes he knows only month & year ("Jan 2010") or even just the year (2010). Is there a standard method to store (and provide input) for that in Rails? I know I could just create 3 separate columns in model, but perhaps there is a nice gem for it.

2
You will have to create 3 columns and custom reader/writer because with only a date column, "2010" will default to "january 1rst 2010". No built-in handler in Rails for this case as far as I know.Damien

2 Answers

2
votes

I created a gem to do exactly this:

http://rubygems.org/gems/date_time_precision

For example:

require 'date_time_precision/format/string'

Date.new(2010, 1).to_s(:long)
# => "January 2010"
0
votes

Have you ever heard of the Chronic gem?

These are some usage examples from the Github documentation.

require 'chronic'

Time.now   #=> Sun Aug 27 23:18:25 PDT 2006

Chronic.parse('tomorrow')
  #=> Mon Aug 28 12:00:00 PDT 2006

Chronic.parse('monday', :context => :past)
  #=> Mon Aug 21 12:00:00 PDT 2006

Chronic.parse('this tuesday 5:00')
  #=> Tue Aug 29 17:00:00 PDT 2006

Chronic.parse('this tuesday 5:00', :ambiguous_time_range => :none)
  #=> Tue Aug 29 05:00:00 PDT 2006

Chronic.parse('may 27th', :now => Time.local(2000, 1, 1))
  #=> Sat May 27 12:00:00 PDT 2000

Chronic.parse('may 27th', :guess => false)
  #=> Sun May 27 00:00:00 PDT 2007..Mon May 28 00:00:00 PDT 2007

Chronic.parse('6/4/2012', :endian_precedence => :little)
  #=> Fri Apr 06 00:00:00 PDT 2012

Chronic.parse('INVALID DATE')
  #=> nil