Best gem to handle parsing of date in a ruby on rails project
I am using a Rails 3 and I need to handle event date. Event model had column called event_date
. To process the user input I have something like
def event_date_s
self.event_date.strftime("%m/%d/%Y") if self.event_date
end
def event_date_s=(date)
if date.blank?
self.event_date = nil
else
self.event_date = Date.s开发者_运维知识库trptime(date, "%m/%d/%Y")
end
end
This quickly gets messy. Is there a gem I can use to handle all this.
Chronic is a great library to handle this. In addition to basic handling of MM/DD/YY dates, etc., it does things like:
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('this tuesday 5:00', :ambiguous_time_range => :none)
#=> Tue Aug 29 05:00:00 PDT 2006
Chronic.parse('may 27th', :now => Time.local(2000, 1, 1))
#=> Sat May 27 12:00:00 PDT 2000
Chronic.parse('may 27th', :guess => false)
#=> Sun May 27 00:00:00 PDT 2007..Mon May 28 00:00:00 PDT 2007
Having the same question I have found timliness https://github.com/adzap/timeliness
I like that it will restrict or validate the format of the input.
Timeliness.parse('2010-09-08 12:13:14', :date, :strict => true) #=> nil
Timeliness.parse('2010-09-08 12:13:14', :time, :strict => true) #=> nil
Timeliness.parse('2010-09-08 12:13:14', :datetime, :strict => true) #=> Wed Sep 08 12:13:14 1000 2010 i.e. the whole string is used
restrict to a format
Timeliness.parse('2010-09-08 12:13:14', :format => 'yyyy-mm-dd hh:nn:ss') #=> Wed Sep 08 12:13:14 UTC 2010
Timeliness.parse('08/09/2010 12:13:14', :format => 'yyyy-mm-dd hh:nn:ss') #=> nil
Extensible with custom formats and tokens. It’s pretty fast. Up to 60% faster than Time/Date parse method. Control the parser strictness. Control behaviour of ambiguous date formats (US vs European e.g. mm/dd/yy, dd/mm/yy). I18n support (for months), if I18n gem loaded. Fewer WTFs than Time/Date parse method. Has no dependencies. Works with Ruby MRI 1.8.*, 1.9.2, Rubinius and JRuby.
精彩评论