Forum: Ruby on Rails RE: calculate age based on DoB

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jonathan V. (Guest)
on 2005-12-20 00:46
(Received via mailing list)
Nice ;)

But are you sure it gives ages 1 year below the real age? Seems to work
fine for me.

-Jonny.
Jeroen H. (Guest)
on 2005-12-20 10:53
(Received via mailing list)
Jonathan V. wrote:
> Nice ;)
>
> But are you sure it gives ages 1 year below the real age? Seems to work
> fine for me.

I apologize! I must have mistyped something when I put it inside my
helper class. Below are two methods, including yours, both work fine.

I find the first method easier to understand. It also make a little more
sense to me to use just the Date class, as we won't be dealing with time
when it comes to birthdays and age. I don't know even know what time I
was born.

def age2(dob)
   date = Date.today
   day_diff = date.day - dob.day
   month_diff = date.month - dob.month - (day_diff < 0 ? 1 : 0)
   date.year - dob.year - (month_diff < 0 ? 1 : 0)
end

def age(dob)
   Time.now.year - dob.year - (((dob.month * 31 + dob.day >
   Time.now.month * 31 + Time.now.day) and
   Time.now.year != dob.year) ? 1 : 0)
end


Jeroen
Jeroen H. (Guest)
on 2005-12-20 11:14
(Received via mailing list)
Jeroen H. wrote:

>
> def age2(dob)
>   date = Date.today
>   day_diff = date.day - dob.day
>   month_diff = date.month - dob.month - (day_diff < 0 ? 1 : 0)
>   date.year - dob.year - (month_diff < 0 ? 1 : 0)
> end
>

def age(dob, date=Date.today)
   day_diff = date.day - dob.day
   month_diff = date.month - dob.month - (day_diff < 0 ? 1 : 0)
   date.year - dob.year - (month_diff < 0 ? 1 : 0)
end

This is a little nicer, gives you the option to return somebody's age at
some given date.

Thanks to Justin F. for this one.

Jeroen
This topic is locked and can not be replied to.