2015-12-19 161 views
0

當選擇從開始日期時,我希望只有3-7天的可能性爲迄今。 所以數據範圍應該是最少3天和最多7天。jquery datepicker更改月份和日期

,現在用下面的代碼工作:

$(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) { 
 
      
 
     }});

我的問題是格式。我想要它像dd-mm-yyyy。但是,當我正確地做到這一點,數據範圍不工作......當我今天接的啓動日期,那麼第一個可能對日期是在一月somewehre ..

確定的解決方案,我現在工作:

$(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) { 
 
      
 
     }}); 
 
});

+0

你能告訴你如何改變日期格式嗎?這可能會提供一個線索,說明爲什麼當你這樣做時它停止工作。 – primehalo

+0

https://jqueryui.com/datepicker/#date-formats – apaul

+0

你可以添加完整的代碼,HTML,CSS和所有? – apaul

回答

1

好了,所以我相信發生了什麼事是你在你的selectedDate日期字符串傳遞(格式爲 'DD-MM-YY')到JavaScript函數日期(),但函數不知道前兩位數字是第二天是一個月,第二天是一年。所以你需要做的是打破selectedDate並將其重新格式化爲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轉換爲全年而不是最後兩位數字。

+0

,我只是把var y = selectedDate.substr(6,4);那一年 – simplesystems

0
var formatedDate = YourDate.toISOString().substring(0, 10); 
相關問題