Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse "X years and Y weeks ago" alike strings in Ruby

Is there a generic parser to parse "... ago" strings and turn them into DateTime objects?

Possible sentences are:

  • 1 year|@count years (and 1 week|@count weeks) ago
  • 1 week|@count weeks (and 1 day|@count days) ago
  • 1 day|@count days (and 1 hour|@count hours) ago
  • 1 hour|@count hours ago (and 1 min|@count min) ago
  • 1 min|@count min ago (and 1 sec|@count sec) ago
  • 1 sec|@count sec ago

So its either a combination of two (Foo and Bar ago) or only one (Foo ago). And it can be singular or plural.

Ruby's DateTime::parse() cannot handle this, nor can DateTime::strptime().

I am hoping for a gem or a snippet somewhere that handles this.

Else I will have to create my own parser, in which case a pointer to how-to-create own DateTime Parsers would be very welcome.

Sidenote: For Future Reference: These are the timestrings generated by Drupals Format Interval

like image 255
berkes Avatar asked Jun 16 '11 21:06

berkes


1 Answers

The Chronic gem may be what you're looking for.

require 'chronic'
Chronic.parse "2 days ago"
# => 2011-06-14 14:13:59 -0700

Per @injekt (one of Chronic's maintainers), you can handle "1 year and 1 week ago" like this:

str = "one year and 1 week ago"
chunks = str.split('and')

Chronic.parse(chunks[1], :now => Chronic.parse(chunks[0] + 'ago'))
#=> 2010-06-09 14:29:37 -0700
like image 187
Dylan Markow Avatar answered Nov 04 '22 07:11

Dylan Markow