Yesterday, while fighting against spam on the Ruby on Rails wiki, I came over a nice gem: Chronic
With Chronic you can easily parse natural language date and time formats into a DateTime object. You don’t have to mess around with regex to parse things manually. As gem, it’s easy to install and it’s also very handy to use.
$ gem install chronic
Thats it.
Put this in your model or controller file:
require 'chronic'
Then you can use Chronic.parse in your methods. E.g. Chronic.parse('tomorrow'),
Chronic.parse('monday', :context => :past), Chronic.parse('this tuesday 5:00')
Or more complex: Chronic.parse('3rd thursday this september'), Chronic.parse('3 months ago saturday at 5:00 pm')
And of course it can do a lot more! For a complete reference and more examples see chronic.rubyforge.org
1 You can also use Chronic to validate malformed date strings: 2 3 class Meeting < ActiveRecord::Base 4 5 def validation 6 errors.add :meeting_date, 'is not a valid date' if Chronic.parse(meeting_date.to_s).nil? 7 end 8 9 end
It is really a nice gem! I used it for my RedBook daily logger, and seems to work well so far.