momentjs将矩形对象添加到数组中

时间:2014-12-29 10:26:31

标签: javascript date momentjs

JS:

service.search = function (goDate, returnDate) {

  var outwardInterval = {};
  outwardInterval.start = moment(goDate, 'YYYY-MM-DD').subtract(3, 'day');
  outwardInterval.end = moment(goDate, 'YYYY-MM-DD').add(3, 'day');

  matrice.outwardDates = buildDateArray(outwardInterval);

}
var buildDateArray = function (interval) {
    var array = [];
    var currentDate = interval.start;
    do {
        array.push(currentDate);
        currentDate.add(1, 'day');
    } while (!currentDate.isAfter(interval.end));

    return array;
};

我的输出:

enter image description here

为什么在我的数组中我有相同的值..?

更新

JSFIDDLE

2 个答案:

答案 0 :(得分:1)

扩展我的评论:

function GetDates(startDate, daysToAdd) {
  var aryDates = [];
  for(var i = 0; i <= daysToAdd; i++) {
   var currentDate = new Date();
   currentDate.setDate(startDate.getDate() + i);
   aryDates.push(DayAsString(currentDate.getDay()) + ", " + currentDate.getDate() + " " + MonthAsString(currentDate.getMonth()) + " " + currentDate.getFullYear());
  }

  return aryDates;
 }

 function MonthAsString(monthIndex) {
  var d=new Date();
  var month=new Array();
  month[0]="Jan";
  month[1]="Feb";
  month[2]="March";
  month[3]="April";
  month[4]="May";
  month[5]="June";
  month[6]="July";
  month[7]="Aug";
  month[8]="Sep";
  month[9]="Oct";
  month[10]="Nov";
  month[11]="Dec";

  return month[monthIndex];
 }

 function DayAsString(dayIndex) {
  var weekdays = new Array(7);
  weekdays[0] = "Sun";
  weekdays[1] = "Mon";
  weekdays[2] = "Tue";
  weekdays[3] = "Wed";
  weekdays[4] = "Thu";
  weekdays[5] = "Fri";
  weekdays[6] = "Sat";

  return weekdays[dayIndex];
 }

 var startDate = new Date();
 var aryDates = GetDates(startDate, 7);
 console.log(aryDates);

小提琴:http://jsfiddle.net/u93g87qc/2/

答案 1 :(得分:-1)

实际上,您没有为数组中的每个值获取相同的日期。你在这里打架moment.js。如果您稍微修改代码以执行toDate的{​​{1}}方法,您会发现它的工作正常:

moment

输出:

var matrice = { };
var service = { };

service.search = function (goDate, returnDate) {

  var outwardInterval = {};
  outwardInterval.start = moment(goDate, 'YYYY-MM-DD').subtract(3, 'day');
  outwardInterval.end = moment(goDate, 'YYYY-MM-DD').add(3, 'day');

  matrice.outwardDates = buildDateArray(outwardInterval);

}

var buildDateArray = function (interval) {
    console.clear();
    console.log('Start: ', interval.start.toDate());
    console.log('End: ', interval.end.toDate());

    var array = [];
    var currentDate = interval.start;

    console.log('Initial date: ', currentDate.toDate());

    do {
        array.push(currentDate.toDate());
        currentDate.add(1, 'days');

        console.log('Current date: ', currentDate.toDate());
    } while (!currentDate.isAfter(interval.end));

    return array;
};

service.search('2014-12-25');