找出从jQuery datepicker中选取的两个日期之间的差异

我有两个文本框,通过jQuery datepickers选择日期。 我想在JavaScript中访问它们,并根据天数找到它们之间的差异。

我通过文本框的clientID访问日期,只是采取差异,但它不适合我。 是否有一些特定的方法来访问通过datepicker填充的文本框中的日期值以及以天为单位查找差异的任何特殊方法?

我的日期字段:

  Select Date   End Date:    Select Date  

我的JavaScript:

 function CheckDuration() { var toDate1 = document.getElementById(''); var toDate2 = new Date(toDate1.value.replace('-', ' ')); var toDate = toDate2.setDate(toDate2.getDate()); var toDate4 = document.getElementById(''); var toDate5 = new Date(toDate1.value.replace('-', ' ')); var toDate6 = toDate2.setDate(toDate2.getDate()); if ((toDate6 - toDate) > 30) confirm("Selected time period is of more than 1 month duration"); } 

有一些内置方法可以从具有日期选择器的输入中获取日期,并且该日期将是一个javascript日期对象,您可以在其上使用getTime()等函数从epoch获取毫秒,然后从中减去一个其他:

 var from_date = $("#from_input").datepicker('getDate'), to_date = $("#to_input").datepicker('getDate'); var diff_in_milliseconds = to_date.getTime() - from_date.getTime(); 

现在你必须弄清楚一天中有多少毫秒?

编辑:

我将为此添加一个示例

小提琴

使用以下Java脚本,您会发现日期之间的差异。 假设有两个名为dtpEventDate = ’06 / 12/2012’且dtpEndDate = ’08 / 12/2012’的方框

 var fa = dtpEventDate.split('/') var ta = dtpEndDate.split('/') // var a = new Date(fa[1]-1,fa[0],fa[2]); // var d = new Date(ta[1]-1,ta[0],ta[2]); for MM-dd-yyyy var a = new Date(fa[2],fa[1]-1,fa[0]); var d = new Date(ta[2],ta[1]-1,ta[0]); // for dd-MM-yyyy 

使用var a和d我们可以找到日期之间的差异

 function CheckDuration() { // alert(""); var toDate1 = document.getElementById('<% =txtStartDt.ClientID%>'); var toDate2 = new Date(toDate1.value.replace('-', ' ')); var toDate = toDate2.setDate(toDate2.getDate()); var toDate4 = document.getElementById('<% =txtEndDt.ClientID%>'); var toDate5 = new Date(toDate4.value.replace('-', ' ')); var toDate6 = toDate5.setDate(toDate5.getDate()); if (toDate && toDate6) { diff = ((toDate6 - toDate) / 86400000); // alert(diff); if(diff>30) return confirm("Selected time period is of more than 1 month duration"); }