Calculate age (years) using DOB and specific date - javascript | XM Community
Skip to main content

I´m trying to use javascript in a date of birthday question to calculate age of the participant on a specific date (11/09/2001 - dd/mm/yyyy). Because after I´m going to display some questions to people who were older that 18 years at that time. I aldready create “age” in embedded data. 

Is this code correct? Because it it not working for me

 

Qualtrics.SurveyEngine.addOnload(function() {
  /* Place your JavaScript here to run when the page loads */

  var dobString = "${q://QID212/ChoiceTextEntryValue}";
  var dobParts = dobString.split("/");
  var dobDate = new Date(dobPartsa2], dobParts21] - 1, dobParts 0]); // Year, Month (0-based), Day

  var targetDate = new Date(2001, 8, 11); // 11th September 2001

  if (!isNaN(dobDate)) {
    var ageInMillis = targetDate.getTime() - dobDate.getTime();

    // Calculate age based on milliseconds
    var years = ageInMillis / (365.25 * 24 * 60 * 60 * 1000);

    // Set the calculated age as embedded data
    Qualtrics.SurveyEngine.setEmbeddedData("age", Math.floor(years));
  } else {
    // Default value in case of invalid dates
    Qualtrics.SurveyEngine.setEmbeddedData("ae", -1);
  }
});

Qualtrics.SurveyEngine.addOnReady(function() {
  /* Place your JavaScript here to run when the page is fully displayed */

  // You can add any additional actions you want to perform here
});

Qualtrics.SurveyEngine.addOnUnload(function() {
  /* Place your JavaScript here to run when the page is unloaded */

  // You can add any cleanup or final actions here
});

Thank you!!!

 


Hmm… the code works for me.

What does not work in your case?
And where did you place the code? (it has to go in a question after your Text Entry question for the age)


@ManfredBM Thanks for the reply! Because when I use display logic for the value created the questions are not appearing to people I want them to appear and vice-versa. So I just assumed that my code was wrong in some way. 

I put the code on the date text entry question. Should I put on other question? 


...

I put the code on the date text entry question. Should I put on other question? 

Yes, the code has to sit on one of the next questions.
The data for your variable ‘dobString’ (${q://QID212/ChoiceTextEntryValue}) is only available after the text entry question was submitted.


I changed that now but still doesn´t work. It is possible that some functions are not being recognized in qualtrics? Like the “split” function or Math.abs …

 

 

 


It worked for me and has calculated the correct result (27 years between 11/09/1974 and 11/09/2001).

Maybe a stupid question:
Does your Text Entry question have the ID “QID212”?

Have you tried to work with the ‘alert()’ command to print out some values of your variables? 
You could for example print the value of ‘dob_entry’ after you have defined this variable.


Yes it is QID212 , I confirmed that just in case. 

I´m going to try to do that. I´m very new at coding but I´ll see if I manage to use that command. 
 

Thank you!


I have a survey question asking the respondent to enter their date of birth. I then need to calculate the age based on the current date. I am struggling to get Qualtrics to do this. I currently have a result showing as miliseconds. 

Question Type is Text Entry

Set Embedded Data:

Current Date = ${date://CurrentDate/m%2Fd%2FY}

DOB Date = ${q://QID3/ChoiceTextEntryValue}

Age Number = $e{(${q://QID3/ChoiceTextEntryValue}-${e://Field/CurrentDate})/365.25}

 

Summary Page:

Age: 4.4767123287936e-7

 

Any help is much appreciated!

Thanks,

BW


@brkwms,

None of the solutions in this thread will always produce the correct answer. So, to solve both your problem and the accuracy problem you should use this.


Thank you for the information. I tried this first thing this morning, but it is still not showing the “Age”. I may have done something incorrectly?

Since my survey is in the “Simple” format, I copied/pasted this code into the header source under Look and Feel/General. 

<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@3.4/build/global/luxon.min.js"></script>

 

I then copied/pasted this part under the question “Enter date of birth” QID3 that is set to “Text entry” question type: 

 

Qualtrics.SurveyEngine.addOnPageSubmit(function() {
    var DateTime = luxon.DateTime;
    var birthDate = DateTime.fromFormat(jQuery(this.getQuestionContainer()).find("inputotype=text]").val(),"MM/dd/yyyy");
    var age = DateTime.now().diff(birthDate, t'years','months']).toObject();
    Qualtrics.SurveyEngine.setJSEmbeddedData('age',age.years);

});

Qualtrics.SurveyEngine.addOnReady(function()
{
    /*Place your JavaScript here to run when the page is fully displayed*/

});

Qualtrics.SurveyEngine.addOnUnload(function()
{
    /*Place your JavaScript here to run when the page is unloaded*/

});

 

In my last survey question set as Text/Graphic

Age in years = ${e://Field/__js_age}

 

In preview, the Age in years: is still blank.

 

 

 


@brkwms,

Two things to check:

  1. You used source mode (<> icon) when you pasted the code in the survey header
  2. Your DOB question is in the format mm/dd/yyyy. Refer to Luxon documentation if you are using a different date format.

That worked! I corrected the header and it is now showing the age. Thank you so much for your help! I’ve been battling this for days!

One last question if you dont mind...Is there a way to include the full age number? Meaning in excel when you calculate the age, the date of birth - current date divided by 365.25 gives you in this case 

Current Date: 09/16/2024

Date of Birth: 04/04/1978

46.453114 


That worked! I corrected the header and it is now showing the age. Thank you so much for your help! I’ve been battling this for days!

One last question if you dont mind...Is there a way to include the full age number? Meaning in excel when you calculate the age, the date of birth - current date divided by 365.25 gives you in this case 

Current Date: 09/16/2024

Date of Birth: 04/04/1978

46.453114 

To return fractional years, can change this line:

var age = DateTime.now().diff(birthDate, t'years','months']).toObject();

to:

var age = DateTime.now().diff(birthDate, t'years']).toObject();

The answer will be more accurate than dividing by 365.25.  


Perfect! Thank you again! I really appreciate it


Leave a Reply