2017-09-01 199 views
0

在我的日期腳本中,當我選擇月份和年份格式時,它會顯示當月的所有日期。它工作正常,但我想dispaly像2017-09-08輸出,但輸出這樣2017-9-8jquery日期選擇器選擇日期格式

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> 
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css"> 
<label for="startDate">Date :</label> 
    <input name="startDate" id="startDate" class="date-picker" /> 
    <div id="datecontent"> 
    </div> 

<script type="text/javascript"> 
var weekday = new Array(7); 
     weekday[0] = "Sunday"; 
     weekday[1] = "Monday"; 
     weekday[2] = "Tuesday"; 
     weekday[3] = "Wednesday"; 
     weekday[4] = "Thursday"; 
     weekday[5] = "Friday"; 
     weekday[6] = "Saturday"; 
$(function() { 
    $('.date-picker').datepicker({ 
     changeMonth: true, 
     changeYear: true, 
     showButtonPanel: true, 
     dateFormat: 'MM yy', 
     minDate: 0, 
     onClose: function(dateText, inst) { 
      $d = new Date(inst.selectedYear, parseInt(inst.selectedMonth)+1, 0).getDate(); 
      $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1)); 
      html=''; 
      for(i=1;i<=$d;i++){ 
       console.log(inst.selectedYear+'-'+(parseInt(inst.selectedMonth)+1)+'-'+i); 
       d = new Date(inst.selectedYear+'-'+(parseInt(inst.selectedMonth)+1)+'-'+i); 
       console.log(d); 
       n = weekday[d.getDay()]; 
       html += '<div class="datediv">div-'+i+'<br>'+n+'</div>'; 
      } 
      $('#datecontent').html(html); 
     } 
    }); 
</script> 

我的輸出

CONSOLE.LOG

2017-9-1 
Fri Sep 01 2017 00:00:00 GMT+0530 (IST) 
2017-9-2 
Sat Sep 02 2017 00:00:00 GMT+0530 (IST) 
2017-9-3 
Sun Sep 03 2017 00:00:00 GMT+0530 (IST) 
2017-9-4 
Mon Sep 04 2017 00:00:00 GMT+0530 (IST) 
2017-9-5 
Tue Sep 05 2017 00:00:00 GMT+0530 (IST) 
2017-9-6 
Wed Sep 06 2017 00:00:00 GMT+0530 (IST) 
2017-9-7 
Thu Sep 07 2017 00:00:00 GMT+0530 (IST) 
2017-9-8 
Fri Sep 08 2017 00:00:00 GMT+0530 (IST) 
2017-9-9 
Sat Sep 09 2017 00:00:00 GMT+0530 (IST) 
2017-9-10 
Sun Sep 10 2017 00:00:00 GMT+0530 (IST) 

我該如何做到這一點?

+0

嘗試在dateformat中將yyyy-mm-dd傳遞給init – pratikpawar

回答

0

在我回答你的問題,我想提一提,時間和日期的處理是a lot deeper比可能先出現它,這通常是不好的做法,推倒重來。考慮使用出色的moment.js解析,處理和顯示您的日期。

就這樣,讓我們​​填零這些日期。

您正在使用parseInt將字符串解析爲整數。但是,01,02,03等都是無效整數 - 您需要輸出字符串。要做到這一點

一種方法是:

function zeroPad(number) 
{ 
    return ('0' + String(number)).slice(-2); 
} 

,你可以調用,如:

console.log(inst.selectedYear+'-'+zeroPad(parseInt(inst.selectedMonth)+1)+'-'+zeroPad(i)); 

請注意,字符串()調用是沒有必要的(JavaScript的隱含類型轉換號碼一個字符串),但我更願意明確這些東西。