且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何计算两个日期之间的天数

更新时间:2021-08-18 02:22:34

http://momentjs.com/ https://date-fns.org/

From Moment docs:

From Moment docs:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days')   // =1

或包含开始:

a.diff(b, 'days')+1   // =2

手动打乱时间戳和时区。

Beats messing with timestamps and time zones manually.

具体取决于您的具体情况用例,你可以

Depending on your specific use case, you can either


  1. 使用 a / b.startOf('day')和/或 a / b.endOf('day')强制差异在结束包含或排除(正如@kotpal在评论)。

  2. 设置第三个参数 true 以获得浮点差异,然后可以 Math.floor Math.ceil Math.round 根据需要。

  3. 选项2也可以通过获取'秒'而不是'days'然后除以 24 * 60 * 60 。

  1. Use a/b.startOf('day') and/or a/b.endOf('day') to force the diff to be inclusive or exclusive at the "ends" (as suggested by @kotpal in the comments).
  2. Set third argument true to get a floating point diff which you can then Math.floor, Math.ceil or Math.round as needed.
  3. Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60.