I have a String 20120119 which represents a date in the format 'YYYYMMDD'.
I want to parse this string into a Ruby object that represents a Date so that I can do some basic date calculation, such as diff against today’s date.
I am using version 1.8.6 (requirement).
You could use the
Date.strptimemethod provided in Ruby’s Standard Library:Alternately, as suggested in the comments, you could use
Date.parse, because the heuristics work correctly in this case:Both will raise an
ArgumentErrorif the date is not valid:If you also want to represent hours, minutes, and so on, you should look at DateTime. DateTime also provides a
parsemethod which works like the parse method onDate. The same goes forstrptime.