Change date range of Adsense Google Sheets report

北城以北 提交于 2020-03-25 17:50:51

问题


How can I change this date range to a specific date?

As I understand it, in the code below it returns the last 7 days.

I need to define a date range, Example:

03/01/2020 to 03/31/2020.

I also need to make this code run automatically daily, without me having to do it manually.

https://developers.google.com/apps-script/advanced/adsense

/**
 * Generates a spreadsheet report for an ad client.
 * @param {string} adClientId The ad client ID
 */
function generateReport(adClientId) {
  // Prepare report.
  var today = new Date();
  var oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);

  var timezone = Session.getTimeZone();
  var startDate = Utilities.formatDate(oneWeekAgo, timezone, 'yyyy-MM-dd');
  var endDate = Utilities.formatDate(today, timezone, 'yyyy-MM-dd');

  var report = AdSense.Reports.generate(startDate, endDate, {
    // Specify the desired ad client using a filter.
    filter: ['AD_CLIENT_ID==' + escapeFilterParameter(adClientId)],
    metric: ['PAGE_VIEWS', 'AD_REQUESTS', 'AD_REQUESTS_COVERAGE', 'CLICKS',
             'AD_REQUESTS_CTR', 'COST_PER_CLICK', 'AD_REQUESTS_RPM',
             'EARNINGS'],
    dimension: ['DATE'],
    // Sort by ascending date.
    sort: ['+DATE']
  });

  if (report.rows) {
    var spreadsheet = SpreadsheetApp.create('AdSense Report');
    var sheet = spreadsheet.getActiveSheet();

    // Append the headers.
    var headers = report.headers.map(function(header) {
      return header.name;
    });
    sheet.appendRow(headers);

    // Append the results.
    sheet.getRange(2, 1, report.rows.length, headers.length)
        .setValues(report.rows);

    Logger.log('Report spreadsheet created: %s',
        spreadsheet.getUrl());
  } else {
    Logger.log('No rows returned.');
  }
}

/**
 * Escape special characters for a parameter being used in a filter.
 * @param {string} parameter The parameter to be escaped.
 * @return {string} The escaped parameter.
 */
function escapeFilterParameter(parameter) {
  return parameter.replace('\\', '\\\\').replace(',', '\\,');
}

来源:https://stackoverflow.com/questions/60566248/change-date-range-of-adsense-google-sheets-report

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!