简体   繁体   English

使用 Moment.JS 计算不同格式的两个日期之间的差异

[英]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.我正在使用 moment.js 来计算 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.日期使用 YY-mm-dd 格式,最后,我得到了天数的差异。

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.问题是当我将嵌入数据'duedate'的格式从 YY-mm-dd 更改为 ISO 8601(例如,2021-10-19T20:30:48Z)时,这会停止工作。

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.我知道我可能还需要将new Date()的格式更改为 ISO,或者将'duedate'重新格式化回 YY-mm-dd,但我正在努力解决这个问题。 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.我以这篇文章为基础,但我是 JavaScript 的初学者,无法弄清楚如何使其工作。

Any help at all is much appreciated!非常感谢任何帮助!

moment.js is pretty smart to understand two different formats and make operations with that dates. moment.js 非常聪明地理解两种不同的格式并使用这些日期进行操作。 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返回 291

Note: I've used Moment.js v2.29.1注意:我使用过 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!感谢大家的洞察力!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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