提问者:小点点

日历禁用下月起的日期


我正在使用JQuery阻止一些日期,但下个月是可用的。一个用户可以点击今天+5,所有其他的都应该被禁用。我做错了什么?

  <div id='datepicker' onchange="test(this)">
  </div>
        
    $('#datepicker').datepicker(
        {
            numberOfMonths: 2,
            beforeShowDay: function (date) {

              
                var hilight = [true, 'isActive'];
                var today = new Date();
                var blockdays = new Date();
               // var startdayofmonth = new Date(today.getFullYear(), today.getMonth(), 1);
                today.setDate(today.getDate() + 5);
                blockdays.setDate(blockdays.getDate() + 12);
                blockdays = moment(blockdays.toLocaleDateString(), 'MM.DD.YYYY').format('YYYY-DD-MM');
                var blockendofmonth = new Date(today.getFullYear(), today.getMonth() + 1, 1);;
                blockendofmonth = moment(blockendofmonth.toLocaleDateString(), 'MM.DD.YYYY').format('YYYY-DD-MM');
                today = moment(today.toLocaleDateString(), 'MM.DD.YYYY').format('YYYY-DD-MM');
                date = moment(date.toLocaleDateString(), 'MM.DD.YYYY').format('YYYY-DD-MM');
               
              
             
                if (date < today) {
                    hilight = [false, ''];
                }
                else if (date >= blockdays) {
                    hilight = [false, ''];
                }

                return hilight;
            }
        }

    );


共1个答案

匿名用户

比较yyyy-dd-mm格式的日期字符串会得到不正确的结果。'2021-10-04'<'2021-20-03'该值的计算结果为true,而这实际上是不正确的。比较日期字符串时,为了获得更好的结果,最好遵循yyyy-mm-dd:hh:mm:ss格式。下面的代码段签出。

null

$(document).ready(function () {
    var allowDays = getAllowDays();
    $('#datepicker').datepicker({
        numberOfMonths: 2,
        beforeShowDay: function (date) {
            var hilight = [true, 'isActive'];
            var start = allowDays[0];
            var end = allowDays[1];
            var currentDate = +moment(date).format('YYYYMMDD');
            if (currentDate < start) {
                hilight = [false, ''];
            } else if (currentDate >= end) {
                hilight = [false, ''];
            }
            return hilight;
        }
    });
});
function getAllowDays() {
    var today = new Date();
    var blockdays = new Date();
    today.setDate(today.getDate() + 5);
    blockdays.setDate(blockdays.getDate() + 12);
    return [+moment(today).format('YYYYMMDD'), +moment(blockdays).format('YYYYMMDD')];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery.ui.datepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css"/>
<div id='datepicker'></div>