Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

javascript - 如何计算两个日期之间的天数(How to calculate number of days between two dates)

I have two input dates taking from Date Picker control.

(我有两个输入日期来自Date Picker控件。)

I have selected start date 2/2/2012 and end date 2/7/2012.

(我选择了开始日期2/2/2012和结束日期2/7/2012。)

I have written following code for that.

(我为此编写了以下代码。)

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

(我应该得到6的结果,但我却得到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?

(谁能告诉我如何获得确切的区别?)

  ask by Vaibhav Deshmukh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

From Moment docs:

(来自Moment文档:)

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

or to include the start:

(或包括开始:)

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

Beats messing with timestamps and time zones manually.

(避免手动打乱时间戳和时区。)

Depending on your specific use case, you can either

(根据您的特定用例,您可以)

  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).

    (使用a/b.startOf('day')和/或a/b.endOf('day')强制diff在“ ends”处包含或不包含(如@kotpal在评论中建议)。)

  2. Set third argument true to get a floating point diff which you can then Math.floor , Math.ceil or Math.round as needed.

    (将第三个参数设置为true可以得到一个浮点差异,然后可以根据需要添加Math.floorMath.ceilMath.round 。)

  3. Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60 .

    (选项2也可以通过获得'seconds'而不是'days' ,然后除以24*60*60 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...