如何在应用脚本中将Google Analytics数据添加到2D数组中

时间:2017-05-08 05:28:18

标签: google-apps-script

我想将谷歌分析的日期作为2017-05-23。但我得到的日期为20170523.代码如下,任何人都可以修改此代码以获得上述日期。

function getReportDataForProfile1(firstProfile) {

  var profileId = firstProfile.getId();
  var tableId = 'ga:' + profileId;
  var startDate = getLastNdays(7);   // 2 weeks (a fortnight) ago.
  var endDate = getLastNdays(0);      // Today.

  var optArgs = {
    'dimensions': 'ga:date,ga:dayOfWeekName,ga:userType',              // Comma separated list of dimensions.
    //'sort': 'ga:pageviews',       // Sort by sessions descending, then keyword.
    //'segment': 'dynamic::ga:isMobile==Yes',  // Process only mobile traffic.
    'filters': 'ga:pagePath=~oho;ga:pagePath=~\\?;ga:pagePath=~accommodation',          // Display only google traffic.
    'start-index': '1',
    //'max-results': '50'                     // Display the first 250 results.
  };

  // Make a request to the API.
  var results = Analytics.Data.Ga.get(
      tableId,                    // Table id (format ga:xxxxxx).
      startDate,                  // Start-date (format yyyy-MM-dd).
      endDate,                    // End-date (format yyyy-MM-dd).
    'ga:pageviews,ga:sessions,ga:sessionDuration,ga:users,ga:bounces,ga:bounceRate,ga:hits', // Comma seperated list of metrics.
      optArgs);

  if (results.getRows()) {
    return results;

  } else {
    throw new Error('No views (profiles) found');
  }
}

1 个答案:

答案 0 :(得分:0)

使用javascript方法match将该数字转换为dateformat,如:

var dateStr = "20170523";
var match = dateStr.match(/(\d{4})(\d{2})(\d{2})/);
var betterDateStr = match[2] + '/' + match[3] + '/' + match[1];
alert(dateStr);

将输出:05/23/2017

查看此SO thread了解详情。