简体   繁体   中英

Argument error : invalid date

What this error could be about? I'm defining an age at my account model:

def age
    birthday = DateTime.new(year_Of_Birth.to_i, month_Of_Birth.to_i, day_Of_Birth.to_i)
    self.age = ((DateTime.now - birthday) / 365.25).to_i
  end

and in my view i get the following error:

ArgumentError - invalid date in the following line:

<dd><%= @account.age %></dd>

Thanks in advance.

Try to test in your Rails app console:

birthday = DateTime.new(1991,4,2)       => Tue, 02 Apr 1991 00:00:00 +0000
DateTime.now - birthday                 => (149073456141953/17280000000)
(DateTime.now - birthday)/365.25        => 23.61926437561592
((DateTime.now - birtday)/365.25).to_i  => 23

This works for me. Check the params that you're setting.

I'm almost sure the arguments that you're passing (year_Of_Birth.to_i, month_Of_Birth.to_i, day_Of_Birth.to_i) have something wrong, debug them and show us the values, or if you want you can try this to catch some specific error:

begin
 birthday = DateTime.new(year_Of_Birth.to_i, month_Of_Birth.to_i, day_Of_Birth.to_i)
 self.age = ((DateTime.now - birthday) / 365.25).to_i
rescue ArgumentError
 #your logic
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM