简体   繁体   English

moment.js - 两个日期之间的差异已关闭

[英]moment.js - difference between 2 dates is off

I'm trying to find the difference between today and a date in the future (number of days) using moment.js.我正在尝试使用 moment.js 找出今天和未来日期(天数)之间的区别。

But the response is always off by 1-2 days.但响应总是在 1-2 天后关闭。

For instance, trying to find the # of days between today (15 June) and 11th July gives me 25 days whereas it should be 27 days.例如,试图找出今天(6 月 15 日)和 7 月 11 日之间的天数给了我 25 天,而应该是 27 天。

Here's what I am using这是我正在使用的

moment(expiryDate).diff(moment(), 'days');

expiryDate is a string of the format YYYY-MM-DD expiryDate是格式YYYY-MM-DD的字符串

I am assuming the difference is because the dates themselves are not included?我假设差异是因为日期本身不包括在内? But nothing in the moment.js document suggests this.但是 moment.js 文档中没有任何内容表明这一点。 Neither did I find anything by which I can tell the library to calculate the difference inclusive of the dates.我也没有找到任何东西可以告诉图书馆计算包括日期在内的差异。

This should do the trick这应该可以解决问题

 console.log( moment("2020-07-11", 'YYYY-MM-DD').diff(moment("2020-06-15", 'YYYY-MM-DD'),"days") ) // outputs 26 (which is correct)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>

I would normalise on 15:00我会在 15:00 恢复正常

 const expiryDate = "2020-06-21"; console.log(moment(expiryDate + " 15:00"),moment({ hour:15 })) console.log( moment(`${expiryDate} 15:00`).diff(moment({ hour:15 }), 'days') )
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>

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

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