Would anyone be able to help me with JS to calculate age in years from a participant’s metadata. My metadata field is called BirthDate and the format is YYYY-MM-DD. This is for a lifecycle survey. I would also need such code for years in service and my metadata is called Hire Date also YYYY-MM-DD
Page 1 / 1
Hello Karen, try using this JS.
Qualtrics.SurveyEngine.addOnload(function() {
// Get the birthdate from the metadata field (assuming it's in YYYY-DD-MM format)
var birthdateStr = "${e://Field/Birthdate}"; // Replace with your actual embedded data field name
// Split the birthdate into an array YYYY, DD, MM]
var birthdateParts = birthdateStr.split('-');
var birthYear = parseInt(birthdatePartss0], 10);
var birthDay = parseInt(birthdatePartss1], 10);
var birthMonth = parseInt(birthdatePartss2], 10);
// Get the current date
var currentDate = new Date();
// Calculate the age based on the birthdate
var age = currentDate.getFullYear() - birthYear;
// Adjust for birthdate if the birthday hasn't occurred yet this year
if (currentDate.getMonth() + 1 < birthMonth || (currentDate.getMonth() + 1 === birthMonth && currentDate.getDate() < birthDay)) {
age--;
}
// Store the age in an embedded data field
Qualtrics.SurveyEngine.setEmbeddedData("CalculatedAge", age);
});
Hi Tushar
Thanks for coming back to me. It doesn’t work…
Do I need to be including any embedded data fields? And also, does the addOnload still work...or should it be Qualtrics.SurveyEngine.addOnReady(function()
Please see this post for a better way (easier and more accurate) to calculate years.
Leave a Reply
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.