Javascript to calculate age from date of birth | XM Community
Question

Javascript to calculate age from date of birth

  • 16 September 2019
  • 2 replies
  • 122 views

Need a question where I calculate age from date of birth. I was using a date picker but it was too complicated when I've got to translate it into four languages with limited javascript knowledge. I am therefore currently using a side by side question with three text inputs for dd, mm and yyyy. This is the code I have so far to calculate the age but it is not working.

Qualtrics.SurveyEngine.addOnReady(function()
{
var day = parseInt("${q://QID87%231/ChoiceTextEntryValue/1/1}");
var month = parseInt("${q://QID87%231/ChoiceTextEntryValue/1/2}") - 1;
var year = parseInt("${q://QID87%231/ChoiceTextEntryValue/1/3}");
var todayInSeconds = new Date().getTime();
var birthdayInSeconds = new Date(year, month, day);
var ageInSeconds = todayInSeconds - birthdayInSeconds;
var ageInYears = Math.floor(ageInSeconds / (1000 * 3600 * 24) / 365);
Qualtrics.SurveyEngine.setEmbeddedData("Age", ageInYears);
}

Any help would be greatly appreciated. Thank you

2 replies

Badge +1
Hi @Sarah646,

You can use DOB question from Qualtrics library and use embedded data to create age buckets.

Thanks,
Bhushan
Userlevel 7
Badge +27
@Sarah646,

I recommend using moment.js for date arithmetic. It makes it a lot easier and solves all the gotcha issues you may run into.

See this comment:
https://www.qualtrics.com/community/discussion/comment/6695#Comment_6695

Leave a Reply