{"day"=>"13", "year"=>"2012", "month"=>"4"} 目前,我在co-6ren">
gpt4 book ai didi

ruby-on-rails - 参数转换的禅宗方式[:date] to Date?

转载 作者:数据小太阳 更新时间:2023-10-29 07:26:09 25 4
gpt4 key购买 nike

params[:date] 字段转换为 Date 对象的最优雅的方法是什么?

"date"=>{"day"=>"13", "year"=>"2012", "month"=>"4"}

目前,我在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

viewform_tag 中:

<%= select_date(@date, :order => [:year, :month, :day], :prefix => 'date') %>

最佳答案

它将返回有效的日期或时间对象。尝试:

@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

关于ruby-on-rails - 参数转换的禅宗方式[:date] to Date?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10136279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com