javascript 在html中计算两个输入类型=“日期”之间的天数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26216565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate number of days between two input type = "date" in html
提问by Pravish
i have this piece of html code where i have two date pickers (input type="date") and a textfield with id="numdays". I want to calculate the number of days between the two selected dates and display the number in my textfield. I also want to restrict selection of a date earlier than today. i think this can be done throught javascript or jquery. Your help would be much appreciated. Thanks.
我有这段 html 代码,其中有两个日期选择器(输入类型 =“日期”)和一个带有 id =“numdays”的文本字段。我想计算两个选定日期之间的天数并在我的文本字段中显示该数字。我还想限制选择比今天早的日期。我认为这可以通过 javascript 或 jquery 来完成。您的帮助将不胜感激。谢谢。
<div id="reserve_form">
<div id="pickup_date"><p><label class="form">Pickup Date:</label><input type="date" class="textbox" id="pick_date" name="pickup_date" </p></div>
<div id="dropoff_date"><p><label class="form">Dropoff Date:</label><input type="date" class="textbox" id="drop_date" name="dropoff_date"/></p></div>
<div id="numdays"><label class="form">Number of days:</label><input type="text" class="textbox" id="numdays" name="numdays"/></div>
</div>
回答by Arindam Nayak
You can do it like this.
你可以这样做。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function GetDays(){
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal(){
if(document.getElementById("drop_date")){
document.getElementById("numdays2").value=GetDays();
}
}
</script>
</head>
<body>
<div id="reserve_form">
<div id="pickup_date"><p><label class="form">Pickup Date:</label><input type="date" class="textbox" id="pick_date" name="pickup_date" onchange="cal()"</p></div>
<div id="dropoff_date"><p><label class="form">Dropoff Date:</label><input type="date" class="textbox" id="drop_date" name="dropoff_date" onchange="cal()"/></p></div>
<div id="numdays"><label class="form">Number of days:</label><input type="text" class="textbox" id="numdays2" name="numdays"/></div>
</div>
</body>