Computing Age from a Date of Birth

From Q
Jump to navigation Jump to search

Sometimes information about the respondents' ages are collected indirectly by asking for their date of birth. If this information is stored in a Date variable, then the following code can be used to compute the respondents' age in years. This code requires you to specify a reference date (e.g. today's date) in order to calculate the age. Please change the date specified in the first line before using this code. This code refers to a Date variable called date. Please replace this with the appropriate Variable Name for your Date of Birth variable.

var reference_dat = Q.AsDate('17/04/2013');
var dob = date;
var age_in_years = NaN;
if (Q.Month(dob) < Q.Month(reference_dat)){
    age_in_years = Q.Year(reference_dat) - Q.Year(dob);
}
else if (Q.Month(dob) == Q.Month(reference_dat) && Q.Day(reference_dat) >= Q.Day(dob)) {
    age_in_years = Q.Year(reference_dat) - Q.Year(dob);
}
else age_in_years = Q.Year(reference_dat) - Q.Year(dob) - 1;
age_in_years;

The resulting question should be set to a Question Type of Pick One or Number.