Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if date is valid?

My code looks like:

if f.thisyear.blank? &&  Date.new(Date.today.year, f.birthday.month, f.birthday.mday ).valid_date?
  f.update_attribute :thisyear, Date.new(Date.today.year, f.birthday.month, f.birthday.mday )
end

In the first line, I check for a valid date using:

Date.new(Date.today.year, f.birthday.month, f.birthday.mday ).valid_date?

This throws an error:

`new': invalid date (ArgumentError)

How do I have to write my code to avoid this problem?

like image 336
Em Sta Avatar asked Dec 12 '22 11:12

Em Sta


1 Answers

Date::valid_date? is a class method, so instead of

Date.new(Date.today.year, f.birthday.month, f.birthday.mday).valid_date?

use

Date.valid_date?(Date.today.year, f.birthday.month, f.birthday.mday)
like image 146
Stefan Avatar answered Dec 31 '22 09:12

Stefan