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).
Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.
The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.
DateTime. strptime('2001-02-03T04:05:06+07:00', '%Y-%m-%dT%H:%M:%S%z') #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...> DateTime. strptime('03-02-2001 04:05:06 PM', '%d-%m-%Y %I:%M:%S %p') #=> #<DateTime: 2001-02-03T16:05:06+00:00 ...>
Parsing is the art of making sense of a bunch of strings and converting them into something we can understand. You could use regular expressions, but they are not always suitable for the job. For example, it is common knowledge that parsing HTML with regular expressions is probably not a good idea.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With