2

我想要这段代码来计算两个日期之间的天数。但它不起作用。我尝试了很多寻找错误但失败了。任何人都可以请帮忙。我浏览了代码,但没有发现任何问题。计算器还是不行!!!

  <!DOCTYPE html>
    <html><head>
     <meta charset="utf-8" />
    <title>jQuery UI Datepicker - Default functionality</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css" />
    <style>
    .ui-datepicker {font-size:11px;}
    </style>
    <script>
    $(function() {
    $( "#from" ).datepicker();
    });
    $(function() {
    $( "#to" ).datepicker();
    });
    </script>
    </head><body>
    <form class="formwhite">
    <table><tr><td>From:</td><td><input type="text" id="from" onKeyUp="calculate();" />&nbsp;
    </td></tr>
    <tr><td>To:</td><td><input type="text" id="to" onKeyUp="calculate();" /></td></tr>
    </table>
    </form>
    <span id="result"></span>
    <script>
    var calculate = function() {
    var from = document.getElementById("from").value;
    var fromdate = from.slice(3, 5);
    fromdate = parseInt(fromdate);
    var frommonth = from.slice(0, 2); 
    frommonth = parseInt(frommonth);
    var fromyear = from.slice(6, 10); 
    fromyear = parseInt(fromyear);
    var to = document.getElementById("to").value;
    var todate = to.slice(3, 5); 
    todate = parseInt(todate);
    var tomonth = to.slice(0, 2); 
    tomonth = parseInt(tomonth);
    var toyear = to.slice(6, 10); 
    toyear = parseInt(toyear);
    var oneDay = 24*60*60*1000;
    var firstDate = new Date(fromyear,frommonth,fromdate);
    var secondDate = new Date(toyear,tomonth,todate);

    var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
    document.getElementById("result").innerHTML=diffDays;
    }
    </script></body></html>
4

2 回答 2

1

把这两行的连字符去掉,改成我这里的。它现在完美运行:

var firstDate = new Date(fromyear,frommonth,fromdate);
var secondDate = new Date(toyear,tomonth,todate);

这是一个链接:http ://dropoff.us/private/1364450059-1-answer1.html

更新:更正了删除按钮的链接并将 onchange 处理程序添加到日期选择器:http ://dropoff.us/private/1364450310-1-answer2.html

于 2013-03-28T05:28:12.180 回答
0

由于您使用的是 jquery datepicker,您可以这样做:

$('#to').datepicker({
   onSelect: function(dateText, inst) { 
       var d1=new Date(dateText);
       var d2=new Date($('#from').val());       
       var diff = (Math.abs((d2-d1)/86400000)); //days between 2 dates
       $("#result").html(diff);
   }
}); 
于 2013-03-28T05:29:58.427 回答