Archive for March, 2010

Extracting date and time from text using Ruby

Problem:
We want to extract a date and time of the format YYYY-MM-DD MM:SS from a body of text using Ruby.
Solution:
This is extremely easy in ruby, and other languages that features regular expressions.

require “Date”

text = “Some text containing a date and a time, for instance 2010-03-19 17:25.”

if text =~ /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})/
dt = DateTime.new($1.to_i, $2.to_i, [...]