ArgumentError: invalid strptime format - `%m/%d/%y' work around

ArgumentError: invalid strptime format - `%m/%d/%y' work around

我正在处理一个 sftp 导入错误,在该错误中我试图标记任何不正确的导入日期。有两种类型的日期可能会关闭。第一个是年份在未来或过去的时间;第二个是实际的月份和日期太高。 (例如,1995 年 13 月 20 日或 2000 年 11 月 35 日)

我正在使用 strptime 并且对于关闭的日期,标记它们并将它们显示为特定消息。我 运行 遇到的问题是,在我使用的 strptime 格式中,错误发生在我加入错误消息之前。

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

错误发生在 birth_date = Date.strptime(date, '%m/%d/%Y') 对于 10/3/1891, 这样的日期,它显示为 Sat, 03 Oct 1891. 但是,对于诸如 33/33/2000 之类的混乱日期,它向我显示了一个错误(这是有道理的),但是我希望在我的条件中修复此错误。

有人知道我能做什么吗?

如果你想使用 strptime 你唯一的选择就是挽救错误:

begin
  birth_date = Date.strptime(date, '%m/%d/%Y')
rescue ArgumentError => ex
  raise ex unless ex.message == 'invalid date'
  # handle invalid date
end

您可以将 date 设置为,例如 :invalid,然后如果您想将所有逻辑保留在那里而不是 [=15],则在您的条件中包含 date == :invalid =]本身。