得到未来五天的一系列天数是失败的

Getting an array of days five days into the future fails

本文关键字:一系列 失败 五天 未来      更新时间:2023-09-26

我使用moment js来获取未来五天的日期

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

代码只生成当前日期。

如果您已经在使用momentjs,那么您似乎通过自己的代码将其功能加倍。

考虑下面的片段:

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"]

我是这样解决的

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