I want to parse some strings into Date object and I find in rdoc that
strptime is the right place to go. For some formats of string it's
really easy to parse it. For instance, '%Y.%m.%d' will parse something
like '2007.09.12'. But I have two kinds of string that I don't now how
to parse.
'20070912': there is no '.', '-' or '/' as the seperator and '%Y%m%d'
doesn't work, it will throw an exception saying that: "ArgumentError: 3
elements of civil date are necessary".
'2007.09': in this kind of string, I don't care about the exactly
date(in fact, the data I received is lacked of that information). As a
result, '%Y.%m' doesn't work with the same error as above.
How can I deal with this two kinds of string? Thanks a lot.
strptime is the right place to go. For some formats of string it's [...]
'20070912': there is no '.', '-' or '/' as the seperator and '%Y%m%d'
doesn't work, it will throw an exception saying that: "ArgumentError: 3
elements of civil date are necessary".
looks like it would be handy if there is something like
Date.strptime("010207", "%2m%2d%2y").to_s
but right now that won't run. maybe it tries to avoid ambiguity.
you can at least use one of these:
a = "20070923"
if match = /^(\d{4})(\d{2})(\d{2}$)/.match(a)
a.replace(match[1..3].join("/"))
puts a
end
'20070912': there is no '.', '-' or '/' as the seperator and '%Y%m%d'
doesn't work, it will throw an exception saying that: "ArgumentError: 3
elements of civil date are necessary".
'2007.09': in this kind of string, I don't care about the exactly
date(in fact, the data I received is lacked of that information). As a
result, '%Y.%m' doesn't work with the same error as above.
How can I deal with this two kinds of string? Thanks a lot.
pieces = str.split(".")
begin
d = Date.new(Integer(pieces[0]), Integer(pieces[1]), 1)
puts d.year #2007
puts d.month #9
rescue ArgumentError
puts "invalid date, e.g. day = 32"
end
I want to parse some strings into Date object and I find in rdoc that
strptime is the right place to go. For some formats of string it's
really easy to parse it. For instance, '%Y.%m.%d' will parse something
like '2007.09.12'. But I have two kinds of string that I don't now how
to parse.
'20070912': there is no '.', '-' or '/' as the seperator and '%Y%m%d'
doesn't work, it will throw an exception saying that: "ArgumentError: 3
elements of civil date are necessary".
'2007.09': in this kind of string, I don't care about the exactly
date(in fact, the data I received is lacked of that information). As a
result, '%Y.%m' doesn't work with the same error as above.
How can I deal with this two kinds of string? Thanks a lot.
rescue ArgumentError
puts "invalid date, e.g. day = 32"
end
Actually, that ArgumentError could be caused by both the Integer() and
the Date.new() methods, so if you want to distinguish between the two
errors, you should convert to an Integer() in a different begin/rescue
block.