JS code to calc data (number of days) difference sometimes blank | XM Community
Skip to main content

Hi All,  (sorry title should have read ‘JS code to calc number of days between two dates but sometimes blank’)

I am seeing some intermittent issues in calculating the difference between two dates using some JS code in a question that is shown at the beginning of my survey.

 

Below is a pic of some example data showing the issue:

  Both the Contact_DIR_Default_Prophet_Segment_Lastmodified and TodayDate embedded fields are being populated ok but sometimes the Days_Since_Prophet_Updated field is not being calculated.

 

I’m aware that often if JS code fails for one reason or another it can return just a blank / null value and so I’m wondering if there is a way I can capture an error code if it fails to understand why.  Is that possible?

 

I’ve manually tested the dates that didn’t work above (console window of my chrome browser) that didn’t show a figure and they work fine.

 

Below is my setup in order of sequence:

 

  1. Survey flow: TodayDate is populated and Days_Since_Prophet_Update field created

     

  1. Survey Flow: Webservice API call looks up contact from a directory and returns the field: Contact_DIR_Default_Prophet_Segment_Lastmodified.  (FYI If the call fails it repeats 3 times through a simple branch logic).

     

  2.  Display block 0c with (intro / welcome letter) with a Text/Graphic question to welcome the respondent and execute the following JS code:
    Qualtrics.SurveyEngine.addOnload(function()
    {
    /*Place your JavaScript here to run when the page loads*/

    //Calulate time since Prophet Segmment was last updated
    var date1 = new Date("${e://Field/Contact_DIR_Default_Prophet_Segment_Lastmodified}").getTime();
    var date2 = new Date("${e://Field/TodayDate}").getTime();

    var diff = parseInt(date2 - date1);
    var days = parseInt(diff/1000/60/60/24);
    //var days = diff;

    Qualtrics.SurveyEngine.setEmbeddedData("Days_Since_Prophet_Updated", days);

    });

     

  3. next block (block 0d) but this only displays when it’s a preview but if you review the response (of any type) in the D&A section you can review the embedded data fields etc.  but it’s just greyed out.  I don’t believe this has any impact in the issues experienced but I’m just mentioning this for completeness

    the below pic is from one which didn’t populate
    Recorded:    September 10, 2025 9:13 AM
    Duration:    00:24:09



    the below pic is from one which did populate

    Recorded:    September 10, 2025 8:27 AM
    Duration:    00:04:25

  4. next block (block 1) NPS and other questions…….

 

So that is the process.  I went to check to see if there was any pattern regarding the browser metadata (browser version devices etc) but unfortunately I’d not taken those details.  I’ve now implemented that question and will come back with some more info if I see a pattern.

But in the meantime, hope someone can advise or can confirm they’ve experienced this sporadic problem too.

 

Thanks

 

Rod Pestell

 

 

a thought…. if the browser or device in question doesn’t like single digit dates or months and this is the reason, would you expect the Days_Since_Prophet_Update field to display NaN instead of being blank or do you have to test for that and update the field accordingly?

 

Is there a different syntax other than ${date://CurrentDate/DS} which delivers a two digit day and month?

 

Thanks


Rod
 


You can use this pipe:

${date://CurrentDate/Y}-${date://CurrentDate/m}-${date://CurrentDate/d}

Also, I suggest using Luxon when doing date calculations because it handles all the oddities involved. 


 

Hi @TomG,

 

Sorry for the long silence.  Just wanted to say thanks for the guidance.  I’ve now used my first Luxon code and it seems to be working, so we’ll see how it performs in the apple devices.  One observation, using the DateTime.fromISO(rawDate1) function seemed to be very strict and wouldn’t accept month or day (ie no error - just returned blank/ NaN in jsfiddle) where it was one digit so hopefully using the fromFormat will suffice.

 

For everyone else reading this, here is a an example script

 

Thanks

 

Rod Pestell

Qualtrics.SurveyEngine.addOnload(function()
{

/*Place your JavaScript here to run when the page loads*/

/*
//===OLD version - doesn't always work on apple devices===
//Calculate time since Segmment was last updated
var date1 = new Date("${e://Field/Contact_DIR_Default_Segment_Lastmodified}").getTime();
var date2 = new Date("${e://Field/TodayDate}").getTime();

var diff = parseInt(date2 - date1);
var days = parseInt(diff/1000/60/60/24);
//var days = diff;

Qualtrics.SurveyEngine.setEmbeddedData("Days_Since_Updated", days);

*/


//===New version - Calculate time since Segment was last updated
// In the header of the survey or the HTML of the question need to add:
// <script src="https://cdn.jsdelivr.net/npm/luxon@3/build/global/luxon.min.js"></script>

// create shortcut / object
const DateTime = luxon.DateTime;

// Get embedded field values
var rawDate1 = "${e://Field/Contact_DIR_Default_Segment_Lastmodified}";
var rawDate2 = "${e://Field/TodayDate}";

// Parse with flexible format (1- or 2-digit month/day)
var Lxn_date1 = DateTime.fromFormat(rawDate1, "yyyy-M-d");
var Lxn_date2 = DateTime.fromFormat(rawDate2, "yyyy-M-d");

// Compute difference
var diffInDays = Lxn_date2.diff(Lxn_date1, "days").days;
var days = Math.floor(diffInDays);

// Store result
Qualtrics.SurveyEngine.setEmbeddedData("Days_Since_Segment_Updated", days);

});

 


@Rod_Pestell,

Glad it worked out. BTW, instead of using Math.floor you could use Luxon’s toObject():

var diff = Lxn_date2.diff(Lxn_date1, ["days", "hours"]).toObject();
Qualtrics.SurveyEngine.setEmbeddedData("Days_Since_Segment_Updated", diff.days);