如何检查日期是否有效(Ruby on Rails)

How to check if date is valid (Ruby on Rails)

我有这个 before_save 功能:

def set_birth_date
    return unless pesel_changed?

    day = pesel[4..5]
    case pesel[2..3].to_i
    when 0..19
      month = pesel[2..3]
      year = pesel[0..1].prepend('19')
    when 20..39
      month = (pesel[2..3].to_i - 20).to_s
      year = pesel[0..1].prepend('20')
    when 40..59
      month = (pesel[2..3].to_i - 40).to_s
      year = pesel[0..1].prepend('21')
    when 60..79
      month = (pesel[2..3].to_i - 60).to_s
      year = pesel[0..1].prepend('22')
    end
      birth_date = Time.strptime("#{day}/#{month}/#{year}", '%d/%m/%Y')
    if birth_date.valid?
      self.birth_date = birth_date
    else
      errors.add(:pesel, I18n.t('activerecord.errors.models.profile.attributes.pesel.invalid'))
    end
  end

(小解释:Last if condition 还没有包含在函数中。我想做的只是保存 birth_date 如果有效,但如果无效,我想添加错误。)但有时它给我这样的错误:

`strptime': invalid date or strptime format - `12/14/2022' `%d/%m/%Y' (ArgumentError)

如何检查 Time.strptime("#{day}/#{month}/#{year}", '%d/%m/%Y') 是否有效? “有效的?”和“valid_date?”不工作。 几个月来我可以做这样的事情

if month / 12 > 0
  <Handling error>
else
  <update>
end

但是几天...这不会那么容易。有什么想法吗?

编辑: pesel 是一个字符串。此函数从 pesel 数字中提取出生日期。 Pesel 数为 11 位数字,例如:

50112014574
50 - year of birth
11 - month of birth
20 - day of birth
14574 - Control number
Those "magic numbers' defines which year someone was born
If someone was born in 19XX, then month number is 1-12.
If someone was born in 20XX, then month number is 21-32 (month number + 20. Example pesel number: '50312014574', which means this person was born 20th November 2050
If someone was born 21XX, then month number is 41-52 (month nubmer + 40) Example pesel number: '50512014574', which means this person was born 20th November 2150 etc.

我正在处理现有的数据库,我不能只验证 pesel 数字

获得年份和月份后,您可能想检查日期是否大于

n_days =  Time.days_in_month(month, year) 

如果您不能首先验证数据库中的 pesel 数字,那么我会捕获错误并在 rescue 块中处理它。

这样做改变

birth_date = Time.strptime("#{day}/#{month}/#{year}", '%d/%m/%Y')

if birth_date.valid?
  self.birth_date = birth_date
else
  errors.add(:pesel, I18n.t('activerecord.errors.models.profile.attributes.pesel.invalid'))
end

begin
  birth_date = Time.strptime("#{day}/#{month}/#{year}", '%d/%m/%Y')
  self.birth_date = birth_date
rescue ArgumentError => e
  errors.add(:pesel, I18n.t('activerecord.errors.models.profile.attributes.pesel.invalid'))
end