Calculate difference between two times | XM Community
Question

Calculate difference between two times

  • 27 May 2023
  • 1 reply
  • 134 views

Userlevel 1
Badge +6
  • Level 2 ●●
  • 16 replies

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. Based on the suggestion of @TomG, I have attempted to do so with moment.js but have not been successful. Any help would be appreciated.

First, I am unsure if I have properly loaded the moment.js library. To do so, I included in the Look & Feel Header:

<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>

 

To calculate time in bed, I attempted the following:

Qualtrics.SurveyEngine.addOnload(function() {

  // Function to calculate and store the time in bed

  function calculateTimeInBed() {

    var timeToBedStr = "${q://QID4/ChoiceTextEntryValue}";

    var timeOutOfBedStr = "${q://QID12/ChoiceTextEntryValue}";

    // Parse the time strings using Moment.js

    var timeToBed = moment(timeToBedStr, 'h:mm A');

    var timeOutOfBed = moment(timeOutOfBedStr, 'h:mm A');

    // Adjust timeOutOfBed if it is on the next day

    if (timeOutOfBed.isBefore(timeToBed)) {

      timeOutOfBed.add(1, 'day');

    }

    // Calculate duration using Moment.js

    var duration = moment.duration(timeOutOfBed.diff(timeToBed));

    var timeInBedMinutes = duration.asMinutes();

    // Store time in bed as an embedded data field

    Qualtrics.SurveyEngine.setEmbeddedData('timeInBed', timeInBedMinutes);

  }

  // Call the calculateTimeInBed function when the page unloads

  Qualtrics.SurveyEngine.addOnUnload(function() {

    calculateTimeInBed();

  });

});

 


1 reply

Userlevel 7
Badge +27

I haven’t really looked at your code, but two things:

  1. You have not loaded moment correctly. It should be:
    <script src="https://cdn.jsdelivr.net/npm/moment@2/moment.min.js"></script>
  2. Luxon has replaced moment, so it would be better to use that.

Leave a Reply