2017-06-06 64 views
2

我想創建這樣的數組。通過moment.js創建日曆數組

var date_ = [ 
{ "DateText": "Mon - 2nd April", "Date": "2/4/2017", "WeekNumber" : 13 }, 
{ "DateText": "Tue - 3rd April", "Date": "3/4/2017", "WeekNumber": 14 }, 
{ "DateText": "Wed - 4th April", "Date": "4/4/2017", "WeekNumber": 14 } 
]; 

我得到了一切只是這第二,第三和第四號碼約定是否存在,你可以檢查我的代碼段。

var date_ = []; 
 

 
var prevDate = moment().subtract(15, 'days'); 
 
var nextDate = moment().add(15, 'days'); 
 

 
var start = new Date(prevDate); 
 
var end = new Date(nextDate); 
 

 
while(start < end){ 
 
    date_.push(
 
     { 
 
     "DateText" : moment(start).format('ddd - DD MMM'), 
 
     "Date" : moment(start).format('DD/MM/YYYY'), 
 
     "WeekNumber" : moment(start).week() 
 
     } 
 
    ); 
 
    var newDate = start.setDate(start.getDate() + 1); 
 
    start = new Date(newDate); 
 
} 
 

 
console.log(date_);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

感謝

回答

3

你需要Do令牌看到Display Format

moment(start).format('ddd - Do MMM') 

var date_ = []; 
 

 
var prevDate = moment().subtract(15, 'days'); 
 
var nextDate = moment().add(15, 'days'); 
 

 
while (prevDate.isBefore(nextDate)) { 
 
    date_.push({ 
 
    "DateText": prevDate.format('ddd - Do MMM'), 
 
    "Date": prevDate.format('DD/MM/YYYY'), 
 
    "WeekNumber": prevDate.week() 
 
    }); 
 
    prevDate.add(1, 'days'); 
 
} 
 

 
console.log(date_);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

+0

完美!謝謝:) – user2972061

+0

+1爲好的答案,但我建議使用['isBefore'](http://momentjs.com/docs/#/query/is-before/)而不是使用'<' – VincenzoC

+1

@VincenzoC,我只專注於OP問題領域_我得到了一切只是這第二,第三和第四號碼約定是剩餘的_你可以修改答案 – Satpal