Reputation: 79
Can someone explain why I'm getting an invalid date error with the following line?
Date.strptime("3082013",'%-m%d%Y')
From my understanding, %-m
should look for a month with no leading 0
. However, executing this code returns
ArgumentError: invalid date
Assuming I can't change the format of the incoming date, what is the best way to deal with this situation?
Upvotes: 0
Views: 171
Reputation: 160611
Sometimes you have to get a bit lower-level, and do what Date.strptime
would do for you:
"3082013".scan(/(\d+) (\d{2}) (\d{4})/x).first
=> ["3", "08", "2013"]
If "308213"
is in MMDDYYYY
format:
mon, day, year = "03082013".scan(/(\d+) (\d{2}) (\d{4})/x).first.map(&:to_i)
=> [3, 8, 2013]
Or, if you know that it's in DDMMYYYY
format, switch mon
and day
:
day, mon, year = "03082013".scan(/(\d+) (\d{2}) (\d{4})/x).first.map(&:to_i)
=> [3, 8, 2013]
Then you can create a Date object:
Date.new(year, mon, day)
=> #<Date: 2013-03-08 ((2456360j,0s,0n),+0s,2299161j)>
Upvotes: 0
Reputation: 10218
The problem is that strptime
does not suppor the minus (-) flag.
Upvotes: 1
Reputation: 3371
Add a zero to the left :
Date.strptime("3082013".rjust(8,'0'),'%-m%d%Y')
Upvotes: 3
Reputation: 29880
You need to add some sort of separator between your month/day/year. Otherwise how will Ruby know whether "3082013" is 3/08/2013 or 30/8/2013?
Upvotes: 0