简体   繁体   中英

How can I customize Rails' date parsing from params?

I want to format dates in jQuery using the UI datepicker like this:

Sunday - 11/28/2010

How/where can I plug in a custom parser for Rails to make it so this works:

def create
  puts params[:event] #=> {"my_date"=>"Sunday - 11/28/2010"}
  event = Event.new(params[:event])
  puts event.my_date #=> nil
end

This works:

def create
  puts params[:event] #=> {"my_date"=>"11/28/2010"}
  event = Event.new(params[:event])
  puts event.my_date #=> Mon, 22 Nov 2010
end

What's the Rails way to do this?

You could use Chronic, a natural language date/time parser

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('may 27th', :guess => false)
#=> Sun May 27 00:00:00 PDT 2007..Mon May 28 00:00:00 PDT 2007

http://chronic.rubyforge.org/

params[:event][:my_date] = Date.parse(params[:event][:my_date])  
event = Event.new(params[:event])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM