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.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
.