Parse "X years and Y weeks ago" same lines in Ruby

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

Possible suggestions:

  • 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 minute | @count min ago (and 1 sec | @count sec) ago
  • 1 s | @count sec ago

So, this is either a combination of two (Foo and Bar back), or only one (Foo back). And it can be singular or multiple.

Ruby DateTime::parse() cannot handle this, and DateTime::strptime() cannot.

I hope for a gem or fragment somewhere that handles this.

Else I will need to create my own parser, in which case a pointer to a way to create my own DateTime Parsers will be very welcome.

Sidenote: For Future Reference: these are timestrings created by Drupals. Spacing between formats

+7
source share
1 answer

Chronic gem may be what you are looking for.

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

Per @injekt (one of the Chronic maintainers), you can handle "1 year and 1 week ago" as follows:

 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 
+9
source

All Articles