Parse natural language date/time strings in Ruby with Chronic

written September 14 2006 by
Kommen
tagged with
, , , ,
1 Comments so far. Go, post one!
Previous Install Mongrel on Ubu…
Mastercard rebranding Next
Migrations in Ruby on Rails
Exception Notifier - Ruby on Rails plugin
State of Web Development 2006
Install Mongrel on Ubuntu 6.06 Dapper

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.

Install it

$ gem install chronic
Thats it.

Use 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

Validate with it

 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

Ressources (Sites I’ve looked at and borrowed the code snippets) for writing this article

1 Comments

Make our day bright and participate!
Permalink to this comment { Fabio Cevasco }
on September 30 2007 (about 23:41 PM)

It is really a nice gem! I used it for my RedBook daily logger, and seems to work well so far.

Do participate!

Textile (only links and basic formatting) is allowed.
These are not required