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.
337cdd270761e0e6f4356de45b04d388?d=identicon&s=25 Jonathan Viney (Guest)
on 2005-12-19 23: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.
B9a732fc30c32098347a0177c75ee27b?d=identicon&s=25 Jeroen Houben (Guest)
on 2005-12-20 09:53
(Received via mailing list)
Jonathan Viney 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
B9a732fc30c32098347a0177c75ee27b?d=identicon&s=25 Jeroen Houben (Guest)
on 2005-12-20 10:14
(Received via mailing list)
Jeroen Houben 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 Forder for this one.

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