Home > Mobile >  Using Moment.JS to calculate difference between two dates in different formats
Using Moment.JS to calculate difference between two dates in different formats

Time:10-20

I'm using moment.js to calculate the difference between two dates in Qualtrics. The code below has worked really well so far. The dates use a YY-mm-dd format, and at the end, I get the difference in days.

const duedate= Qualtrics.SurveyEngine.getEmbeddedData('duedate');
const daystodue = moment(duedate).diff(moment(new Date()), 'days', false);
Qualtrics.SurveyEngine.setEmbeddedData('daystill', daystodue );

The problem is when I change the format for the embedded data 'duedate' from YY-mm-dd to ISO 8601 (e.g., 2021-10-19T20:30:48Z) this stops working.

I know I'd probably need to change the format for new Date() to ISO as well, or re-format 'duedate' back to YY-mm-dd, but I'm struggling to figure this out. This is what I tried:

const duedate= Qualtrics.SurveyEngine.getEmbeddedData('duedate');
const daystodue = moment(duedate).diff(moment(new Date().format("YYYY-MM- 
DDTHH:mm:ssZ")), 'days', false);
Qualtrics.SurveyEngine.setEmbeddedData('daystill', daystodue );

I was basing myself on this article, but I'm a beginner in JavaScript and couldn't figure out how to make it work.

Any help at all is much appreciated!

CodePudding user response:

moment.js is pretty smart to understand two different formats and make operations with that dates. I've tried this and it works:

const dueDate = '2021-10-19T20:30:48Z'
const firstDayOfYear = '2021-01-01'
moment(dueDate).diff(moment(firstDayOfYear), 'days', false)

returns 291

Note: I've used Moment.js v2.29.1

CodePudding user response:

I ended up putting this together, which works:

const duedate= Qualtrics.SurveyEngine.getEmbeddedData('duedate');
const today= new Date( );
const daystodue= moment(duedate).diff(moment(today), 'days', false);
Qualtrics.SurveyEngine.setEmbeddedData('daystill', daystodue);

Thank you all for your insight!

  • Related