简体   繁体   中英

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

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 (eg, 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!

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM