jquery datepicker - 计算日期差异

时间:2012-01-17 20:57:47

标签: javascript jquery

我是新来的,我真的需要你的帮助,因为我一直在努力奋斗好几天...... 我想计算使用datepicker选择的两个日期之间的天数。我是在正确的轨道上还是我完全错了?我所知道的是,当我点击天数时,它没有显示任何内容。这是我的代码

    <!DOCTYPE html>
    <html>
    <head>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
      <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
      <script>
        $(document).ready(function () {

            $("#datepicker").datepicker({ minDate: "01/07/2012", maxDate: "01/30/2012" });

            $("#datepicker1").datepicker({ beforeShow: setminDate });

            var start1 = $('#datepicker');      
            function setminDate() {          
                var p = start1.datepicker('getDate');          
                if (p) { 
                    var k ="01/30/2012";            
                    return {
                    minDate: p,
                    maxDate:k
                }};         
            }           
            function clearEndDate(dateText, inst) {          
                end1.val('');      
            }  
        });
    $(function() {
        $( "#datepicker1" ).datepicker({ dateFormat: 'mm/dd/yyyy' });
        $( "#datepicker" ).datepicker({ dateFormat: 'mm/dd/yyyy' });
    });
    $('button').click(function() {
        var start = $('#datepicker1').datepicker('getDate');
        var end   = $('#datepicker').datepicker('getDate');
        var days   = (end - start)/1000/60/60/24;
        alert(days);
    });
    </script>
    <body>
    <form>
        from: 
        <input id="datepicker" readonly='true'/><br>
        to: 
        <input id="datepicker1" readonly='true'/><br>
    </form>
        <br><button>number of days</button>

    </body> 
    </html>

1 个答案:

答案 0 :(得分:12)

在进行此项更改后为我工作

    var start = $('#datepicker').datepicker('getDate');
    var end   = $('#datepicker1').datepicker('getDate');
    var days   = (end - start)/1000/60/60/24;
    alert(days);

jsfiddle:http://jsfiddle.net/diode/L2et3/3/