如何计算两个日期之间的天数 [英] How to calculate number of days between two dates

查看:149
本文介绍了如何计算两个日期之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个输入日期来自日期选择器控件。我选择了开始日期2/2/2012和结束日期2/7/2012。我已经为此编写了以下代码。

I have two input dates taking from Date Picker control. I have selected start date 2/2/2012 and end date 2/7/2012. I have written following code for that.

我应该得到结果为6但我得到5。

I should get result as 6 but I am getting 5.

function SetDays(invoker) {   
    var start = $find('<%=StartWebDatePicker.ClientID%>').get_value();
    var end = $find('<%=EndWebDatePicker.ClientID%>').get_value();

    var oneDay=1000 * 60 * 60 * 24;
    var difference_ms = Math.abs(end.getTime() - start.getTime())
    var diffValue = Math.round(difference_ms / oneDay);
}

谁能告诉我如何才能得到确切的区别?

Can anyone tell me how I can get exact difference?

推荐答案

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'然后除以<$来完成c $ c> 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.

这篇关于如何计算两个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆