RE: calculate age based on DoB

Nice :wink:

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

-Jonny.

Jonathan V. wrote:

Nice :wink:

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. 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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs