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

Javascript to calculate age from date of birth

  • September 16, 2019
  • 2 replies
  • 162 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

Bhushan
QPN Level 2 ●●
Forum|alt.badge.img+1
  • QPN Level 2 ●●
  • 22 replies
  • September 16, 2019
Hi @Sarah646,

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

Thanks,
Bhushan

TomG
Level 8 ●●●●●●●●
Forum|alt.badge.img+27
  • Level 8 ●●●●●●●●
  • 5909 replies
  • September 16, 2019
@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