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, $3.to_i, $4.to_i, $5.to_i)
end

RSS feed | Trackback URI

1 Comment »

Comment by prince
2010-12-28 06:05:00

you can also use DateTime.strptime(“2010-03-19 17:25”, “%Y-%m-%d %M:%S”)

 
Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> in your comment.