Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The zen way of convert params[:date] to Date?

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') %>
like image 555
ohho Avatar asked Feb 20 '23 20:02

ohho


1 Answers

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
like image 166
Vik Avatar answered Mar 02 '23 18:03

Vik