提问者:小点点

jquery datepicker更改月份和日期


当选择开始日期时,我希望只有3-7天的可能性才是开始日期。因此,数据周期应为最小3天,最大7天。

现在可以使用以下代码:

null

 $(function() {
      $.datepicker.setDefaults({minDate: 0, changeMonth: true, numberOfMonths: 1});
      $('#datepicker').datepicker({onSelect: function(selectedDate) {
       
            var newToDateStart=new Date(selectedDate);
            newToDateStart.setDate(newToDateStart.getDate()+3)
            var newToDateEnd=new Date(selectedDate);
            newToDateEnd.setDate(newToDateEnd.getDate()+7);
          
            $('#datepicker1').datepicker('option', 'minDate', newToDateStart);
          $('#datepicker1').datepicker('option', 'maxDate', newToDateEnd);
            setTimeout(function() { $('#datepicker1').focus(); }, 0);
      }});
      $('#datepicker1').datepicker({onSelect: function(selectedDate) {
            
      }});

null

我的问题是格式。我想要像dd-mm-yyyy一样。但当我这样做时,数据范围不能正常工作...当我选择今天作为开始日期,那么第一个可能的日期是在一月份…

现在对我有效的OK解决方案:

null

$(function() {
      $.datepicker.setDefaults({minDate: 0, changeMonth: true, numberOfMonths: 1, dateFormat: 'dd-mm-yy'});
      $('#datepicker').datepicker({onSelect: function(selectedDate) {
        $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' });


        var d = selectedDate.substr(0,2); // retrieve the day from the string
        var m = selectedDate.substr(3,2); // retrieve the month from the string
        var y = selectedDate.substr(6,4); // retrive the year from the string
        var newToDateStart=new Date(y,m-1,d); // month is zero-based, so subtract 1
        newToDateStart.setDate(newToDateStart.getDate()+3)

        var newToDateEnd=new Date(y,m-1,d);
        newToDateEnd.setDate(newToDateEnd.getDate()+7);

            $('#datepicker1').datepicker({ dateFormat: 'dd-mm-yy' });
            $('#datepicker1').datepicker('option', 'minDate', newToDateStart);
          $('#datepicker1').datepicker('option', 'maxDate', newToDateEnd);
            setTimeout(function() { $('#datepicker1').focus(); }, 0);
      }});
      $('#datepicker1').datepicker({onSelect: function(selectedDate) {
            
      }});
}); 

null


共2个答案

匿名用户

好的,所以我相信发生的事情是,您将selectedDate日期字符串(格式为'dd-mm-yy')传递到JavaScript函数date()中,但该函数不知道前两位数是日,后两个是月,第三个是年。因此,您需要做的是分解所选的date并将其重新格式化为date()可以识别的日期字符串(例如MM/DD/YYYY),或者将其分解为单独的数字并传递给它们,例如:

var d = selectedDate.substr(0,2); // retrieve the day from the string
var m = selectedDate.substr(3,2); // retrieve the month from the string
var y = selectedDate.substr(6,2); // retrive the year from the string
var newToDateStart=new Date(y,m-1,d); // month is zero-based, so subtract 1

注意:如果年份类似于15,并且将其按原样传递到Date()中,则Date()可能认为是1915年,而不是2015年。因此,根据您的需要,您可能希望将y转换为一整年,而不是仅仅转换为最后两位数。

匿名用户

var formatedDate = YourDate.toISOString().substring(0, 10);