Reputation: 2174
I am in the process of working with an sftp import bug in which I'm trying to flag any dates that are imported that are incorrect. There are two types of dates that could be off. The first is when the year is in the future, or way in the past; the second is when the actual months and days are too high. (Example, 13/20/1995, or 11/35/2000)
I'm using strptime
and for dates that are off, flagging them and displaying them as a specific message. The problem I'm running into is that with the strptime
format that I'm using, the errors happen right before I sub in the error message.
table_birth_dates = self.class.connection.execute("SELECT birth_date FROM #{temp_table_name}").values.flatten
table_birth_dates.map! do |date|
birth_date = Date.strptime(date, '%m/%d/%Y')
if birth_date.nil?
month_day_error_message = 'Invalid Month/Day'
elsif birth_date > Time.zone.today
future_error_message = 'Year in Future'
elsif birth_date.year < 1900
past_error_message = 'Year too old'
else
birth_date
end
end
The error is happening at the birth_date = Date.strptime(date, '%m/%d/%Y')
For a date such as 10/3/1891,
it displays them as Sat, 03 Oct 1891.
However, for the messed up dates such as 33/33/2000
it shows me an error (which makes sense) however I was hoping to fix this error in my conditional.
Would anyone know what I could do?
Upvotes: 0
Views: 4261
Reputation: 96994
If you want to use strptime
your only option really is to rescue the error:
begin
birth_date = Date.strptime(date, '%m/%d/%Y')
rescue ArgumentError => ex
raise ex unless ex.message == 'invalid date'
# handle invalid date
end
You could set date
to, e.g., :invalid
there and then have date == :invalid
in your conditional if you want to keep all the logic there instead of in the rescue
itself.
Upvotes: 1