Need to calculate the date difference to use in question piping | XM Community
Skip to main content

I have a survey where, depending on whether someone has responded to a block before and whether 365 days have passed since then, they should either skip it or see it.

 

I’m using a directory for authentication and saving the last completion date as MM_LastSurveyDate to compare with current date. 

MM_LastSurveyDate = empty → in the beginning of survey flow

MM_LastSurveyDate = ${date://CurrentDate/Y%2Fm%2Fd} → when they complete that survey and it is recorded in the directory. This embedded field exists after the block in question is completed so it updates in the directory. The set up for the update is already done and working.

 

I’m struggling to set up the 365-day condition, because I don’t know how to calculate the difference between two dates and how to add it into the survey flow.

 

For more context, I haven’t used JavaScript before, so I have no idea what I’m doing. I tried to set this up in the survey flow with embedded fields, but had absolutely no luck.

 

Heeelp pleaseee 

UPDATE: Solved

Just in case it helps someone else…..

I’ve solved this with adding this code to the first question on the questionnaire:

Qualtrics.SurveyEngine.addOnPageSubmit(function() {
var lastDateStr = "${e://Field/MM_LastSurveyDate}";
if (lastDateStr && lastDateStr.trim() !== "") {
var parts = lastDateStr.split('/');
var lastDate = new Date(partsa0], partsa1]-1, partsa2]);
var today = new Date();
var diffTime = today - lastDate;
var diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
Qualtrics.SurveyEngine.setEmbeddedData('__js_DaysSinceLastSurvey', diffDays);
console.log("Days since last survey: " + diffDays);
} else {
Qualtrics.SurveyEngine.setEmbeddedData('__js_DaysSinceLastSurvey', 9999);
console.log("No last survey date found. Setting to 9999.");
}
});

and adding the embedded field __js_DaysSinceLastSurvey in the beginning of the survey flow along with MM_LastSurveyDate


Update: solved.