What's the most elegant way of converting a params[:date]
field to a Date
object?
"date"=>{"day"=>"13", "year"=>"2012", "month"=>"4"}
Currently, I have the following code in the controller
:
@date = Date.current
if params[:date]
yy = mm = dd = 0
yy = params[:date][:year].to_i if params[:date][:year]
mm = params[:date][:month].to_i if params[:date][:month]
dd = params[:date][:day].to_i if params[:date][:day]
@date = Date::civil(yy, mm, dd) if Date::valid_date?(yy, mm, dd)
end
and inside the view
's form_tag
:
<%= select_date(@date, :order => [:year, :month, :day], :prefix => 'date') %>
It will return the valid date or time object . Try :
@date = Date.parse("#{params[:date]['day']}-#{params[:date]['month']}-#{params[:date]['year']}") if params[:date]
OR
@date = Time.parse("#{params[:date]['day']}-#{params[:date]['month']}-#{params[:date]['year']}") if params[:date]
@date ||= Date.current
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With