Scott W
Scott W

Reputation: 79

Why do I get an "invalid date" error for %-m%d%Y"?

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

Answers (4)

the Tin Man
the Tin Man

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

Lu&#237;s Ramalho
Lu&#237;s Ramalho

Reputation: 10218

The problem is that strptime does not suppor the minus (-) flag.

Upvotes: 1

pierallard
pierallard

Reputation: 3371

Add a zero to the left :

Date.strptime("3082013".rjust(8,'0'),'%-m%d%Y')

Upvotes: 3

Logan Serman
Logan Serman

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

Related Questions