# RE: calculate age based on DoB

**URL:** <https://www.ruby-forum.com/t/re-calculate-age-based-on-dob/72889>\
**Category:** Rails\
**Created:** [December 19, 2005, 11:46pm UTC](https://www.ruby-forum.com/t/re-calculate-age-based-on-dob/72889 "2005-12-19T23:46:33Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jonny](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/47e85d/32.png) [@jonny](https://www.ruby-forum.com/u/jonny)\
**Post date:** [December 19, 2005, 11:46pm UTC](https://www.ruby-forum.com/t/re-calculate-age-based-on-dob/72889/1 "2005-12-19T23:46:33Z")

</div>

Nice 😉

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

-Jonny.

---

<div class="post-metadata">

**Author:** ![jonny](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/47e85d/32.png) [@jonny](https://www.ruby-forum.com/u/jonny)\
**Post date:** [December 20, 2005, 9:53am UTC](https://www.ruby-forum.com/t/re-calculate-age-based-on-dob/72889/2 "2005-12-20T09:53:40Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![jonny](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/47e85d/32.png) [@jonny](https://www.ruby-forum.com/u/jonny)\
**Post date:** [December 20, 2005, 10:14am UTC](https://www.ruby-forum.com/t/re-calculate-age-based-on-dob/72889/3 "2005-12-20T10:14:43Z")

</div>

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
