# Calculate age based on DoB

Hi,

I wrote a little helper that calulates someone’s age based on his/her
date of birth.

def age(dob)
diff = Date.today - dob
age = (diff / 365.25).floor
age.to_s
end

It works fine, but it’s not completely accurate as it just takes the
average days in a year. It should be able to calculate this more
accurately, right? I can’t work it out though…

Jeroen

Jeroen H. wrote:

Hi,

I wrote a little helper that calulates someone’s age based on his/her
date of birth.

def age(dob)
diff = Date.today - dob
age = (diff / 365.25).floor
age.to_s
end

It works fine, but it’s not completely accurate as it just takes the
average days in a year. It should be able to calculate this more
accurately, right? I can’t work it out though…

Jeroen

Give this a try Jeroen:

def get_age(dob)
return nil unless dob
now = Time.now
now.year - dob.year - (dob.to_time.change(:year => now.year) > now ? 1
: 0)
end

now.year - dob.year - (dob.to_time.change(:year => now.year) > now ?
1

Nifty. It can’t handle dobs before 1970 though.

Here’s one that’s not optimized in any way, but it is accurate:

def age(dob)
unless dob.nil?
a = Date.today.year - dob.year
b = Date.new(Date.today.year, dob.month, dob.day)
a = a-1 if b > Date.today
return a
end
nil
end

Here’s one that’s not optimized in any way, but it is accurate:

Good but fails on leap days.

d = Date.new(2000,2,29)
age(d) #throws exception

Sean S. wrote:

Ouch. Okay so does anyone have a method for turning a date object into
an age which works for both dates before 1970 and leap days?

Here’s one for Brian to test:

def age_at(date, dob)
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

Both arguments must be Dates.

regards

Justin

Brian B. wrote:

Here’s one that’s not optimized in any way, but it is accurate:

Good but fails on leap days.

d = Date.new(2000,2,29)
age(d) #throws exception

Ouch. Okay so does anyone have a method for turning a date object into
an age which works for both dates before 1970 and leap days?

Justin F. wrote:

d = Date.new(2000,2,29)
def age_at(date, dob)
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

Both arguments must be Dates.

Works fine for me. Also handles pre 1970 dates just fine.
Thanks!

Jeroen

def age(dob)
unless dob.nil?
years = Date.today.year - dob.year
if Date.today.month < dob.month
years = years + 1
end
if (Date.today.month == dob.month and
Date.today.day < dob.day)
years = years - 1
end
return years
end
nil
end

Frank