Google Apps脚本:获取两个日期之间的日期数组

时间:2016-11-28 13:20:55

标签: google-apps-script

我正在制作时间表电子表格。我想通过输入开始日期和结束日期来包含允许用户输入休假期间的功能,然后自动标记其间的日期。我有以下内容,它根据相关的开始和结束日期输入值,但不输入两者之间的日期。有没有可以构建一个日期数组,然后我可以循环呢?

function updateLeave() {
 var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Front Page");
 var startDate = ss.getRange("C15").getValue();
 var endDate = ss.getRange("C16").getValue();
 var type = ss.getRange("C17").getValue(); 
 var creditTime = ss.getRange("C18").getValue();

 var allSheets = SpreadsheetApp.getActiveSpreadsheet();
 var sheets = allSheets.getSheets();
 sheets.forEach (function (sheet) {

 var columnB = sheet.getRange(2, 2, 70, 1); 
 var bValues = columnB.getValues(); 
 var today = startDate; 
 for (var i = 0; i < bValues.length; i++) { 
 var fDate = new Date(bValues[i][0]);
 if (fDate.getDate() == today.getDate() && 
    fDate.getMonth() == today.getMonth() && 
    fDate.getFullYear() == today.getFullYear()) { 
    sheet.getRange(i + 2, 10, 1, 1).setValue(type);
    sheet.getRange(i + 2, 9, 1, 1).setValue(creditTime);  
}
}
})

sheets.forEach (function (sheet) {

var columnB = sheet.getRange(2, 2, 70, 1); 
var bValues = columnB.getValues(); 
var today = endDate; 
for (var i = 0; i < bValues.length; i++) { 
var fDate = new Date(bValues[i][0]);
if (fDate.getDate() == today.getDate() && 
    fDate.getMonth() == today.getMonth() && 
    fDate.getFullYear() == today.getFullYear()) { 
    sheet.getRange(i + 2, 10, 1, 1).setValue(type);
    sheet.getRange(i + 2, 9, 1, 1).setValue(creditTime);  
}
}

})
}

1 个答案:

答案 0 :(得分:0)

这样的事情怎么样:

var DAY_MILLIS = 24 * 60 * 60 * 1000;

function main() {
  var a = new Date('2016/01/01');
  var b = new Date('2016/01/03');
  var dates = createDateSpan(a, b);
}

function createDateSpan(startDate, endDate) {
  if (startDate.getTime() > endDate.getTime()) {
    throw Error('Start is later than end');
  }

  var dates = [];

  var curDate = new Date(startDate.getTime());
  while (!dateCompare(curDate, endDate)) {
    dates.push(curDate);
    curDate = new Date(curDate.getTime() + DAY_MILLIS);
  }
  dates.push(endDate);
  return dates;
}

function dateCompare(a, b) {
  return a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate();
}

main函数显示了一个使用示例