当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Getting an array of days five days into the future fails

问题描述:

I am using moment js to get the date five days into the future with this code

//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

and now i am attempting to get an array of days between current date and the future date which is five days later

//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);

});

This is the demo https://jsfiddle.net/codebreaker87/z9d5Lusv/67/

The code only generates the current date. How can i generate an array of all dates between?.

网友答案:

If you are using momentjs already, then you seem to be doubling its functinality by your own code.

Consider the following snip:

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"]
网友答案:

I managed to solve it like this

//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);
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: