0

我正在使用 jQuery datepicker 来选择日期范围。下面的代码获取日期范围的开始日期input1和结束input2日期。但是我如何简单地获得两者之间的日期?谢谢你的建议!

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <link type="text/css" href="../demoengine/demoengine.css" rel="stylesheet">
    <script type="text/javascript" src="../demoengine/demoengine.js" async defer></script>
    <title>jQuery UI Datepicker: Using Datepicker to Select Date Range</title>
    <link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/ui-darkness/jquery-ui.css" rel="stylesheet">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
    <style type="text/css">
        .dp-highlight .ui-state-default {
            background: #484;
            color: #FFF;
        }
    </style>
</head>
<body>
    <div id="datepicker"></div>
    <p>
        Dates:
        <input type="text" id="input1" size="10">
        <input type="text" id="input2" size="10">
    </p>
    <script type="text/javascript">
        $(function() {
            $("#datepicker").datepicker({
                beforeShowDay: function(date) {
                    var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
                    var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
                    return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];
                },
                onSelect: function(dateText, inst) {
                    var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
                    var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
                    if (!date1 || date2) {
                        $("#input1").val(dateText);
                        $("#input2").val("");
                        $(this).datepicker("option", "minDate", dateText);
                    } else {
                        $("#input2").val(dateText);
                        $(this).datepicker("option", "minDate", null);
                    }
                }
            });
        });
    </script>
</body>
</html>
4

1 回答 1

0

In order to get the dates between date1 and date2 you can just add one day in a for-loop until you reach the end date. The date object provides a setDate method, which allows to go beyond the end of month (like August 32nd and just wraps it to September 1st for you).

for(; date1 < date2; date1.setDate(date1.getDate() + 1)) {
    alert(date1);
}
于 2013-09-14T13:30:02.537 回答