Ruby Chronic gem - parse datetime in natural language

To parse natural language datetime string in Ruby, we can use gem Chronic. Chronic is a natural language date parser in Ruby. This comes very handy, if we want to parse natural language datetime input from user to Time / DateTime classes.

Sometimes, we need to parse datetime string in Ruby. To parse datetime string in Ruby, we can use Time / DateTime classes.

Check out the post on parsing datetime with timezones here.

If we want to parse datetime string which is in natural language, Time, DateTime classes can not handle the parsing. That is where Chronic gem comes in handy.

Install Chronic Gem

Source: Chronic gem on Github

Unfortunately, the github pages for the gem is not maintained any more. To install chronic gem in Ruby, perform the command given below.

gem install ruby
Use Chronic with Rails

If we want to use chronic gem with Ruby on Rails application then, add this to Gemfile.

gem "chronic", "~> 0.10.2"

0.10.2 is latest stable version. Or we can say 0.10.2 is the last release of the gem. There is no active development on Chronic gem anymore.

Usage of Chronic gem

To use the gem for parsing, require the gem if not already.

require "chronic"
# => true

Listing down time when below tests were run.

Time.now
# => 2018-06-03 19:10:11 +0530
Chronic gem capabilities
Parse Output
Chronic.parse("today") 2018-06-03 21:00:00 +0530
Chronic.parse("tomorrow") 2018-06-04 12:00:00 +0530
Chronic.parse("2 days ago") 2018-06-01 19:08:29 +0530
Chronic.parse("2 days from now") 2018-06-05 19:09:22 +0530
Chronic.parse("A week ago") 2018-05-27 19:10:28 +0530
Chronic.parse("A week from now") 2018-06-10 19:10:52 +0530
Chronic.parse("2 weeks ago") 2018-05-20 19:11:58 +0530
Chronic.parse("2 weeks from now") 2018-06-17 19:12:21 +0530
Chronic.parse("2 fortnights ago") 2018-05-06 19:12:47 +0530
Chronic.parse("a month ago") 2018-05-03 19:13:38 +0530
Chronic.parse("5 months ago") 2018-01-03 19:14:14 +0530
Chronic.parse("A year before") 2017-06-03 19:15:34 +0530
Chronic.parse("A year from now") 2019-06-03 19:15:16 +0530

So, as we can see chronic gem supports parsing around below listed date time related fields.

  • day
  • week
  • fortnight
  • month
  • year

If chronic is not able to parse date time string, it returns nil response as given below.

Chronic.parse("invalid date")
# => nil

Chronic gem can throw an error, if it is not able to figure out the datetime string for parsing.

Chronic.parse("A week and 3 days ago")
# NoMethodError: undefined method `start=' for nil:NilClass
#  from gems/chronic-0.10.2/lib/chronic/handlers.rb:517:in `get_anchor`
# => nil
Conclusion

Chronic gem comes in really handly when we want to parse datetime string input in natural language. This can be a input from a user or a configuration in the system to be done by support staff for an application.