2016-11-04 48 views
0

我使用的時刻JS來獲得之日起五年日內到未來這段代碼獲得天的數組5天到未來失敗

//current date 
var cd = moment().format("DD-MM-YYYY"); 
//5 days into the future 
var nd = moment(cd, "DD-MM-YYYY").add(5, 'days').format('DD-MM-YYYY'); 
//get all dates from today to 5 days into the future 

,現在我試圖讓天之間的陣列current datethe future date這是五天後

//current date 
var cd = moment().format("DD-MM-YYYY"); 
//5 days into the future 
var nd = moment(cd, "DD-MM-YYYY").add(5, 'days').format('DD-MM-YYYY'); 
//get all dates from today to 5 days into the future 

console.log("start",cd); 
console.log("end",nd); 

var getDates = function(startDate, endDate) { 
    var dates = [], 
     currentDate = startDate, 
     addDays = function(days) { 
     var date = new Date(this.valueOf()); 
     date.setDate(date.getDate() + days); 
     return date; 
     }; 
    while (currentDate <= endDate) { 
    dates.push(currentDate); 
    currentDate = addDays.call(currentDate, 1); 
    } 
    return dates; 
}; 

// Usage 
var dates = getDates(cd, nd);                           
dates.forEach(function(date) { 
    console.log(date); 
}); 

此爲演示https://jsfiddle.net/codebreaker87/z9d5Lusv/67/

該代碼僅生成當前日期。我怎樣才能生成所有日期之間的數組?

回答

0

我管理,如果您正在使用momentjs已經解決像這樣

//current date 
var cd = moment().format("YYYY-MM-DD"); 
//5 days into the future 
var nd = moment(cd, "YYYY-MM-DD").add(5, 'days').format('YYYY-MM-DD'); 
//get all dates from today to 5 days into the future 


var getDates = function(startDate, endDate) { 
    var dates = [], 
     currentDate = startDate, 
     addDays = function(days) { 
     var date = new Date(this.valueOf()); 
     date.setDate(date.getDate() + days); 
     return date; 
     }; 
    while (currentDate <= endDate) { 
    dates.push(currentDate); 
    currentDate = addDays.call(currentDate, 1); 
    } 
    return dates; 
}; 

var dates = getDates(new Date(cd), new Date(nd));                          
dates.forEach(function(date) { 
//format the date 
var ald = moment(date).format("YYYY-MM-DD"); 
    console.log(ald); 
    console.log(date); 
}); 
1

,那麼你似乎是由你自己的代碼中增加了一倍functinality。

考慮以下剪斷:

var getDates = function(cd, nd){ 
    var dates = []; 
    var now = cd.clone(); 
    for(var i = 0; i < nd.diff(cd, 'days') ; i++){ 
     // format the date to any needed output format here 
     dates.push(now.add(i, 'days').format("DD-MM-YYYY")); 
    } 
    return dates; 
} 

var r = getDates(moment(), moment().add(10, 'days')); 

// r now contains 
["04-11-2016", "05-11-2016", "07-11-2016", "10-11-2016", "14-11-2016", "19-11-2016", "25-11-2016", "02-12-2016", "10-12-2016", "19-12-2016"]