# Calculating Age in Years from Date of Birth

## Source code:

```Problem
You want to calculate someone's age in years using a formula field, given a date of birth.

Solution
Here's a formula that will calculate the exact age from the birth date.  We assume you've got the date stored in a field DOB__c.

[code apex]
IF(
MONTH(TODAY())>MONTH(DOB__c),
YEAR(TODAY())-YEAR(DOB__c),
IF(AND(MONTH(TODAY()) = MONTH(DOB__c), DAY(TODAY()) >= DAY(DOB__c)),
YEAR(TODAY())-YEAR(DOB__c),
(YEAR(TODAY())-YEAR(DOB__c))-1)
)
[/code]

Description

The formula works by checking several cases:

First: if the month of present year is greater than date of birth, then the age will be calculated as the difference between present year and year of birth.

Secondly: if the months of the two dates are the same, but today's day is larger than or equal to the day of the date of birth, then the age is calculate as in the first scenario.

Thirdly: if both of these scenarios fail, then we have a day of birth before before the present day, in which case the age is calculated as the difference between present year and year of birth, subtracting 1.
```