Ruby date_select conversion

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article
Posted by John
on Wednesday, 19 March 2008

Had a bit of a pain with Ruby's handling of Date/Time values coming from a Date_Select form element, managed to solve it though.

The problem was that in my form...

<%=date_select(:date,'',:start_year => 1950,:include_blank => false, :default => { :year => '1970' })%>

...the value I got back from the submitted field,

params[:date]

became...

'(3i)4(1i)1953(2i)5'

Bit of a mess, obviously I was expecting something a little more legible like 1953-5-4 (yyyy-mm-dd), so I bashed my head against a brick wall trying to work it out, I could have made my life easier with some select_date blocks but I'm a guy how likes to ask 'why' so I perceviered.

Turns out in my travels you can do this to break it into a usable DateTime object..

Time.mktime(params[:date]['(1i)'],params[:date]['(2i)'],params[:date]['(3i)'])

Which will return something much more legible...

Sun May 19 00:00:00 +0100 1968

Or whip it into a method to do exactly what you want...

def convert_date(obj)
  return "#{obj['(1i)']}-#{obj['(2i)']}-#{obj['(2i)']}"
end

<%=convert_date(params[:date])%>

But wait, it doesn't end there, you could use Date.new or Date.civil to parse it into a real date object like...

def convert_date(obj)
  return Date.new(obj['(1i)'].to_i,obj['(2i)'].to_i,obj['(3i)'].to_i)    
end

Which will return...

1967-03-19

Much nicer, just remember to use .to_i otherwise you'll get...

comparison of String with 0 failed

Enjoy!