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
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();
});
});