Search code examples
javascriptmomentjsqualtricsflatpickr

Calculate difference between two times on Qualtrics


Respondents record a start time (time to bed) and and end time (time out of bed) in separate questions using flatpickr’s time picker. The responses are recorded in the format, for example, 11:00 PM and 8:00 AM, for start time and end time respectively.

I need to calculate time in bed = (time out of bed - time to bed) in minutes.

To calculate time in bed, I attempted the following:

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

});

Qualtrics.SurveyEngine.addOnReady(function()
{
      // get the values of the start and end time questions
    var timeToBed = "${q://QID4/ChoiceTextEntryValue}";
    var timeOutOfBed = "${q://QID12/ChoiceTextEntryValue}";


    // create Date objects for the start and end times
    var timeToBedDate = new Date("1/1/2000 " + timeToBed);
    var timeOutOfBedDate = new Date("1/1/2000 " + timeOutOfBed);
    

    // check if the end time is before the start time (i.e. the times are on different days)
    if (timeOutOfBed < timeToBed) {
        timeOutOfBedDate.setDate(timeOutOfBedDate.getDate() + 1);
    }
    
    // calculate the difference in minutes
    var timeInBedMinutes = (timeOutOfBedDate - timeToBedDate) / 1000 / 60;

    // save the difference as an embedded data variable
    Qualtrics.SurveyEngine.setEmbeddedData("timeInBed", timeInBedMinutes);

});

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

});

Solution

  • If you want to use moment you can try using this code:

    const timeToBedDate = moment("11:15 PM", "HH:mm A"); // HH:mm A is the format of the time you pass, if you need a specific date it's to change something
    const timeOutOfBedDate = moment("8:05 AM", "HH:mm A");
    
    console.log(timeToBedDate.format()); // 2023-06-20T23:15:00+02:00
    console.log(timeOutOfBedDate.format()); // 2023-06-21T08:05:00+02:00
    
    if (timeOutOfBedDate.isBefore(timeToBedDate)) timeOutOfBedDate.add(1, 'day'); // Add one day if the out of bed is before go to bed
    
    const timeInBedMinutes = timeOutOfBedDate.diff(timeToBedDate, 'minutes'); // Calculate the difference between two date
    console.log(timeInBedMinutes); // 530 minutes
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

    Basically I create two moment objects from the time string, and specify what format I'm passing it to them (with HH:mm A). I add a day in case the dates are reversed (as you did). At the end I use the diff function to calculate the minutes from one date to the other, if you also want decimals you have to insert a third boolean parameter.