如何在 Google Apps 脚本中删除今天的 Google 日历条目

问题描述 投票:0回答:1

我正在尝试删除 Google Apps 脚本中今天的 Google 日历条目。 我从 Google 电子表格创建条目。 在单元格中,日期格式为 mm/dd/yyyy 00:00:00,其中开始日期和结束日期相等,从而创建在 Google 日历上显示为全天条目的内容。

这是我用来创建条目的代码:

function addEntries() {
  
  var calendarId = "calID"; // Please set your calendar ID.

  // Retrieve values from Spreadsheet.
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Calendar_Data");
  var lastRow = sheet.getLastRow();
  var data = ss.getRange("A2:E" + lastRow).getValues();
  
  // Create a request body for the batch request.
  var colorObj = { "PALE_BLUE": 1, "PALE_GREEN": 2, "MAUVE": 3, "PALE_RED": 4, "YELLOW": 5, "ORANGE": 6, "CYAN": 7, "GRAY": 8, "BLUE": 9, "GREEN": 10, "RED": 11 };
  var requests = data.map(([summary, description, dateObj, , color]) => {
    const date = Utilities.formatDate(dateObj, Session.getScriptTimeZone(), "yyyy-MM-dd");
    return {
      method: "POST",
      endpoint: `https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events`,
      requestBody: { end: { date }, start: { date }, description, colorId: colorObj[color], summary }
    }
  })
  
  // Request the batch request using the created request body.
  var result = BatchRequest.EDo({ batchPath: "batch/calendar/v3", requests });
  console.log(result);
}

当我尝试删除今天的条目时,代码运行没有错误,但没有删除或记录任何条目。 我认为这与我在

deleteTodayEntries()
函数中的开始和结束日期有关。 这是我尝试过的代码:

function deleteTodayEntries() {
  var calendarID = "calID"; // Please set your calendar ID.

  var today = new Date();
  var startDate = new Date(today.getDate());
  var endDate = new Date(today.getDate());
  var calendar = CalendarApp.getCalendarById(calendarID);
  var existingEvents = calendar.getEvents(startDate, endDate);


  // Create a request body for the batch request.
  var requests = existingEvents.map(e => ({
    method: "DELETE",
    endpoint: `https://www.googleapis.com/calendar/v3/calendars/${calendarID}/events/${e.getId().split("@")[0]}`,
  }));

  // Request the batch request using the created request body.
  var result = BatchRequest.EDo({ batchPath: "batch/calendar/v3", requests });
  console.log(result);
}

有人可以指出我在这里缺少什么吗? 谢谢你。

google-sheets google-apps-script google-calendar-api
1个回答
0
投票

阅读Class Calendar文档,我发现了这个函数:

getEventsForDay()
。 我已将代码更改为:

function deleteTodayEntries() {
  var calendarID = "calID"; // Please set your calendar ID.

  
  var today = new Date();
  var calendar = CalendarApp.getCalendarById(calendarID);
  var existingEvents = calendar.getEventsForDay(today);


  // Create a request body for the batch request.
  var requests = existingEvents.map(e => ({
    method: "DELETE",
    endpoint: `https://www.googleapis.com/calendar/v3/calendars/${calendarID}/events/${e.getId().split("@")[0]}`,
  }));

  // Request the batch request using the created request body.
  var result = BatchRequest.EDo({ batchPath: "batch/calendar/v3", requests });
  console.log(result);
}

现在我的代码可以运行了。

© www.soinside.com 2019 - 2024. All rights reserved.