在我的代码中,我有以下内容
const today = moment();
const someday = moment('Wed Oct 10 2018 13:50:00 GMT-0400 (Eastern Daylight Time)');
const diff = today.diff(someday, "days");
const diff2 = today.diff(someday);
out.innerText = diff;
out2.innerText = moment.utc(diff2 * 1000).format("D[ day(s)] H[ hour(s)] m[ minute(s)]");
我期望diff和diff2具有相同的日期,但diff返回正确的日期,而diff2返回错误的数据。此处的格式化有何不同?
JSFiddle:link
最佳答案
尝试:
out2.innerText = moment.duration(diff2).asDays();
这将为您提供十进制的天数(不进行utc转换),并且与您在
today.diff(someday, "days")
中看到的相匹配。您可以按照所需的X天Y小时Z分钟的方式自行设置格式,如下所示:
const theDuration = moment.duration(diff2);
out2.innerText = Math.floor(theDuration.asDays()) + " day(s) " +
theDuration.hours() + " hour(s) " + theDuration.minutes() + " minute(s)";
只需确保时区在您输入的日期格式/您正在计算的计算机上的时钟/所需的用户输出之间匹配即可。这是docs页面上的有用概述:local / utc。
我还看到提到的矩持续时间格式库很有用:https://github.com/jsmreese/moment-duration-format
尝试:
out2.innerText = moment.utc(diff2).format("DDDD [ day(s)] H[ hour(s)] m[ minute(s)]");
在格式字符串(moment.js .format docs)中使用“年的日”(DDDD)代替“月的日”(DD),并在
* 1000
构造函数中删除不必要的.utc
,因为就像提到的Jb31一样,diff2已经在毫秒。根据Jb31的说法,当差异日达到365时,这是一个非常糟糕的主意。关于javascript - diff momentjs天vs毫秒产生不同的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57046127/