# Calculate the age using a year (or year and month) variable

As a full birth date might be considered personally identifiable information, using only the birth year or year and month of birth is a good alternative. It is still possible to calculate the age from these variables using a calculation field (although with less precision).

### Calculate the age of a patient from a birth year

```var a = moment();
var b = moment('{dem_pat_birthyear}', 'YYYY');
var diff = a.diff(b, 'years'); // calculates patient's age in years
diff; // this prints out the age```

In this calculation {dem_pat_birthyear} needs to be replaced with your variable name for birth year.

Note: in the first line, moment(); is used to automatically calculate today's date. This date will be updated once the data entry for a record is opened.

### Calculate the age using a text field

If you are using a text field to collect only month and year of birth, you can use the following template to calculate the age:

```var a = moment();
var b = moment('{dem_pat_birthyear}', 'MM-YYYY');
var age = moment.duration(a.diff(b));
var years = age.years();
var months = age.months();
"The age is " + years + " years " + months + " months ";```

In this calculation {dem_pat_birthyear} needs to be replaced with your variable name for birth year.

### Calculate the age of a patient from the birth year and a visit date

```var birthyear = moment('{patient_birthyear}', 'YYYY');
var visitdate = moment('{baseline_visit}', 'DD-MM-YYYY');
visitdate.diff(birthyear, 'y');```

In this calculation {patient_birthyear} needs to be replaced with your variable name for birth year and {baseline_visit} for the visit date. Test this calculation in the calculation helper.

To calculate the age using an actual date field, use this template.

or drag and drop files