Convert DOB to Age | XM Community
Skip to main content
Solved

Convert DOB to Age

  • 19 April 2023
  • 5 replies
  • 1114 views

Hi there, 

I have a recruitment survey. One of the questions is “When were you born?” It’s a text entry question in this date format (MM/DD/YYYY). Does anyone know how I can convert this answer into an age? 

Thanks in advance!

5 replies

Userlevel 7
Badge +39

@aaban You can customize this:

Age calculator HTML Code for website | HTML Form Guide

Hope it helps!

Badge +2

@Deepak - Thanks for sending! Where in the question would you place this code (e.g. after addOnload)?

Userlevel 5
Badge +19

Hi @aaban ,
You can calculate the age by incorporating above code as below:
First create a an embedded data named “age” and next the QID of the text question on which you will add the below code and take date as input.
Now before applying below code you have to add the below line of  html code in the <> ) (HTML)of header in look and feel:
 

<script src="https://cdn.jsdelivr.net/npm/pikaday/pikaday.js"></script>
<link href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css" rel="stylesheet" type="text/css" />

 




Now , add below code in your date question:
 

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

});

Qualtrics.SurveyEngine.addOnReady(function()
{
function calculateAge(date)
{
const now = new Date();
const diff = Math.abs(now - date );
const age = Math.floor(diff / (1000 * 60 * 60 * 24 * 365));
return age
}

var picker = new Pikaday({
field: document.getElementById('QR~QID45') ,
yearRange:[1900,2020],
onSelect: function(date) {
let age = calculateAge(date);
Qualtrics.SurveyEngine.setEmbeddedData('age', age);
}



});


calculateAge();


});

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

});


This code calculates age and store it in the embedded data “age” which you can use anywhere by piping.
Hope this resolves your query😊!!
 

Badge +2

@qualtrics_nerd - THANK YOU! It worked. I didn’t realize you needed to add something to the header.

Badge +2

Hello @qualtrics_nerd ,

Never mind. I got it to work! Thank you for posting the solution!

Leave a Reply