JS to calcuate age in years and service in years from metadata | XM Community
Skip to main content
Question

JS to calcuate age in years and service in years from metadata


Forum|alt.badge.img+6

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

3 replies

TusharDalwani
QPN Level 6 ●●●●●●

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(birthdateParts[0], 10);
    var birthDay = parseInt(birthdateParts[1], 10);
    var birthMonth = parseInt(birthdateParts[2], 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);
});

 


Forum|alt.badge.img+6
  • Author
  • QPN Level 2 ●●
  • 9 replies
  • February 3, 2025

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()


TomG
Level 8 ●●●●●●●●
Forum|alt.badge.img+27
  • Level 8 ●●●●●●●●
  • 5926 replies
  • February 3, 2025

@karen_split-pin,

Please see this post for a better way (easier and more accurate) to calculate years.


Leave a Reply