使用<input type =“date”/>减去两个日期

时间:2015-12-05 09:15:37

标签: javascript jquery html5 date

我在尝试从两个日历选择中获取日期时遇到基本问题,并将它们放入下面的计算中。

任何人都有解决方案吗?

由于 伊恩

&#13;
&#13;
<body>
  <h1>Project Details</h1>

  <h3>Please enter the project Notice to Proceed (NTP) date: <input     id="NtpDate" type= "date" name="NtpDate"></h3>
  </br>
  <h3>Please enter the Report date: <input type= "date" name="ReportDate">    </h3>

  <script type="text/javascript">
    // I would like to replace this with the <input type = date> tags ...var     NtpDate = new Date("7/11/2004");
     // I would like to replace this with the <input type = date> tags ...	var      ReportDate = new Date("12/12/2010");	

    var timeDiff = Math.abs(ReportDate.getTime() - NtpDate.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
     //alert(diffDays);
    document.write("Period =" + diffDays + " (Days from NTP)");
  </script>`
</body>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:0)

重复问题How to calculate date difference in javascript

但这就是你获得两个datepicker的价值的方法。 var ReportDate = document.getElementById('ReportDate').value;

答案 1 :(得分:0)

编辑:Updated fiddle

您可以尝试以下方式:

<h3>Please enter the project Notice to Proceed (NTP) date: <input id="NtpDate" type= "date" name="NtpDate"></h3>

<h3>Please enter the Report date: <input type= "date" name="ReportDate" id="abc"></h3>

$("#abc").on("change", function () {
  var olddate = new Date($("#NtpDate").val());
  var newdate = new Date($(this).val());
  var timeDiff = Math.abs(newdate.getTime() - olddate.getTime());
  var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
  alert(diffDays);
});

<强> DEMO FIDDLE

答案 2 :(得分:0)

   <body>
  <h1>Project Details</h1>

  <h3>Please enter the project Notice to Proceed (NTP) date: <input     id="NtpDate" type= "date" name="NtpDate"></h3>
  </br>
  <h3>Please enter the Report date: <input id="ReportDate" type= "date" name="ReportDate" onchange="myFunction()">    </h3>

  <script type="text/javascript">

myFunction = function(){

alert(document.getElementById("NtpDate").value +" >> "+document.getElementById("ReportDate").value)
   

 var NtpDate = new Date(document.getElementById("NtpDate").value);
	
var ReportDate = new Date(document.getElementById("ReportDate").value);	

var timeDiff = Math.abs(ReportDate.getTime() - NtpDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
 //alert(diffDays);
alert("Period =" + diffDays + " (Days from NTP)");}
  </script>`
</body>

答案 3 :(得分:0)

momentJS非常适合日期操作和格式化。由于闰日等原因,你永远不会完全正确地完成它。

时刻就像:

moment('some date').diff('other date', 'days')

moment.diff()