jQuery Datepicker日计数

Sco*_*own 2 javascript jquery jquery-ui datepicker

我有两个jQuery UI日期选择器,当他们都选择了日期时,我希望这些日期之间的差异在input[type="text"]选择第二个日期后立即显示.

另外,理想情况下,我希望减去任何周末时间,只计算周一至周五的天数.

我的(相关)代码如下:

JS:

$('#firstday, #lastday').datepicker({
  dateFormat: 'dd/mm/yy'
});
Run Code Online (Sandbox Code Playgroud)

XHTML:

<label for="firstday">First Day of Leave</label>
<input type="text" name="firstday" id="firstday" />

<label for="lastday">Last Day of Leave</label>
<input type="text" name="lastday" id="lastday" />

<label for="totaldays">Total Days</label>
<input type="text" name="totaldays" id="totaldays" />
Run Code Online (Sandbox Code Playgroud)

大量的搜索使我得到了许多不同的解决方案,我无法按照自己的意愿去工作,所以任何想法都会受到赞赏.

Kru*_*ule 6

这样的事情应该有效:

$("#firstday, #lastday").datepicker({
  onSelect: function (){

    // Date will give time difference in miliseconds, that is why we divide with 1000*60*60*24

    var firstday = new Date($("#firstday").val().split("/").reverse().join(","));
    var lastday = new Date($("#lastday").val().split("/").reverse().join(",");
    $("#totaldays").val((lastday - firstday) / 86400000);        
  }
});
Run Code Online (Sandbox Code Playgroud)

在节点控制台中,它提供:

> x = new Date("18/5/2010".split("/").reverse().join(","))
Mon, 17 May 2010 22:00:00 GMT
> y = new Date("18/5/2015".split("/").reverse().join(","))
Sun, 17 May 2015 22:00:00 GMT
> x-y
-157766400000
> y-x
157766400000
> (y-x)/86400000
1826
Run Code Online (Sandbox Code Playgroud)

- 编辑 -

当你有开始日期和结束日期周末的天数很容易使用getDay()从周日的0,周一的1和星期六的6返回.

Yo也可以使用.getMonth()和.getDate()以及其他一些其他{}条件.

var weekend_count = 0;
for (i = firstday.valueOf(); i <= lastday.valueOf(); i+= 86400000){
 var temp = new Date(i);
 if (temp.getDay() == 0 || temp.getDay() == 6) {
   weekend_count++;
 }
}
Run Code Online (Sandbox Code Playgroud)

你最后会这样做

$("#totaldays").val( (lastday - firstday) / 86400000 - weekend_count);
Run Code Online (Sandbox Code Playgroud)

只是为了在最后做一个说明.你应该在一个单独的函数中推断这段代码(尽可能多),以便让你的代码更容易维护,以防你在其他地方需要相同的功能.

祝好运.