0

我正在使用 jQuery 日期选择器。我能够计算两个选定日期之间的天数,但我需要能够选择一个日期范围(选择'fromdate'成为'todate'的'minim',选择'todate'成为'maxim'从日期')。我正在使用这段代码:

<script type="text/javascript">
$(document).ready(function () { 
var selector = function (dateStr) {
        var d1 = $('.fromdate').datepicker('getDate');
        var d2 = $('.todate').datepicker('getDate');
        var diff = 1;
        if (d1 && d2) {
            diff = diff + Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
        }
        $('.calculated').val(diff);
        $('.minim').val(d1)
    }
$('.fromdate').datepicker({
                dateFormat : 'yy-mm-dd',
                changeMonth: true,
                changeYear: true,
                minDate: 'minim'
});
$('.todate').datepicker({ 
                dateFormat : 'yy-mm-dd',
                changeMonth: true,
                changeYear: true,
                minDate: 'fromdate'
});
$('.fromdate,.todate').change(selector)
});
</script>

谢谢!

4

2 回答 2

2

看看这个演示链接,这将帮助您计算两个所选日期之间的天数,并能够选择一个日期范围。

$('.fromdate').datepicker().bind("change", function () {
    var minValue = $(this).val();
    minValue = $.datepicker.parseDate("yy-mm-dd", minValue);
    $('.todate').datepicker("option", "minDate", minValue);
    calculate();
});
$('.todate').datepicker().bind("change", function () {
    var maxValue = $(this).val();
    maxValue = $.datepicker.parseDate("yy-mm-dd", maxValue);
    $('.fromdate').datepicker("option", "maxDate", maxValue);
    calculate();
});

我希望这能帮到您。

于 2013-02-26T09:51:48.613 回答
0

感谢 Bojan Kovacevic,我设法解决了我的问题。它是这样的:

<script type="text/javascript">
$(document).ready(function () { 
var selector = function (dateStr) {
        var d1 = $('.fromdate').datepicker('getDate');
        var d2 = $('.todate').datepicker('getDate');
        $('.fromdate').datepicker("option", "maxDate",d2); //new line           
        $('.todate').datepicker("option", "minDate",d1); // new line
        var diff = 1;
        if (d1 && d2) {
            diff = diff + Math.floor((d2.getTime() - d1.getTime()) / 86400000);
        }
        $('.calculated').val(diff);
        $('.minim').val(d1)
    }    
$(".fromdate").datepicker({
                dateFormat : 'yy-mm-dd',
                changeMonth: true,
                changeYear: true,
});
$('.todate').datepicker({
                dateFormat : 'yy-mm-dd',
                changeMonth: true,
                changeYear: true,
                minDate: ($(".fromdate").is(":visible") && $(".todate").html() != ""? $('.todate').datepicker('getDate'): 'null'), // new line
});
$('.fromdate,.todate').change(selector)
});

于 2013-02-26T10:17:19.637 回答