You could use the Date.strptime
method provided in Ruby's Standard Library:
require 'date'
string = "20120723"
date = Date.strptime(string,"%Y%m%d")
Alternately, as suggested in the comments, you could use Date.parse
, because the heuristics work correctly in this case:
require 'date'
string = "20120723"
date = Date.parse(string)
Both will raise an ArgumentError
if the date is not valid:
require 'date'
Date.strptime('2012-March', '%Y-%m')
#=> ArgumentError: invalid date
Date.parse('2012-Foo') # Note that '2012-March' would actually work here
#=> ArgumentError: invalid date
If you also want to represent hours, minutes, and so on, you should look at DateTime. DateTime also provides a parse
method which works like the parse method on Date
. The same goes for strptime
.