Skip to content

Rails and Chronic, easy ‘smart’ date fields

There are quite a few Ruby on Rails plugins to give you nice Calendar drop downs for date selection...but, I'm much more partial to the style of fuzzy date entry you see in a lot of apps now, allowing you to enter common strings and have the app figure out the date -- ie, "next friday", "tomorrow", etc. With a pointer from Mike yesterday to the excellent Chronic gem, I was on my way.

Chronic does all the hard work, just install it...

CODE:
  1. gem install chronic

Then, in your views, use a text_field for your date...

RUBY:
  1. <% form_for :model do |f| %>
  2. <% f.text_field :date_attr_name %>
  3. <% end %>

In your model, you'll want to then use Chronic to parse the pre-cast value of the date attribute using the _before_type_cast methods...

RUBY:
  1. require 'chronic'
  2.  
  3. class MyModel <ActiveRecord::Base
  4.  
  5.   def before_save
  6.     self.date_attr_name = Chronic.parse(self.date_attr_name_before_type_cast) if self.date_attr_name_before_type_cast
  7.   end
  8.  
  9. end

I expect I'm going to find that I need to tweak this a little -- and I'm pretty sure I'll want to write a helper that will give the user a AJAX preview of the parsed date before the submit the form, but, it definitely beats the lousy Rails built-in date_select method.

Categories: Ruby on Rails.

Comment Feed

3 Responses

  1. Thank you. Thank you. Excellent short and sweet tutorial for this. Helps clear things up for how to use Chronic.

  2. Tx for the helpful tutorial.

    In line 2 of the second example, I think that the code has to be ”



Some HTML is OK

or, reply to this post via trackback.

Continuing the Discussion

Switch to our mobile site