Google Ads 指令碼通常需要處理日期和時間。常見用途包括擷取特定日期範圍的報表、排定廣告活動或廣告群組在特定時間放送,以及將指令碼上次執行的時間輸出至試算表。本指南說明在 Google Ads 指令碼中使用日期和時間時的重要概念、常見陷阱和建議做法。
基本概念
如要在 Google Ads 指令碼中使用日期和時間,請使用 JavaScript 內建的日期物件。JavaScript 日期物件代表特定時間點。建立新日期物件的方式如下:
// Create a date object for the current date and time.
const now = new Date();
// Create a date object for a past date and time using a formatted string.
const date = new Date('February 17, 2025 13:00:00 -0500');
// Create a copy of an existing date object.
let copy = new Date(date);
新指令碼使用者經常對日期物件處理時區的方式感到困惑。以單一時區的時鐘時間來思考日期物件是錯誤的,但也是很自然的想法。舉例來說,在先前的程式碼片段中,部分使用者會誤以為 date 僅在一個時區有效,也就是建立該時區時使用的時區 (時差為 -5 小時)。在該錯誤檢視中,date 需要「轉換」才能在其他時區使用。
正確的做法是將日期物件視為特定時間點,與任何時區無關。雖然不同時區的時鐘顯示的時間不同,但指的都是同一時刻。舉例來說,請參考以下程式碼片段:
// Create two date objects with different times and time zone offsets.
const date1 = new Date('February 17, 2025 13:00:00 -0500');
const date2 = new Date('February 17, 2025 10:00:00 -0800');
// getTime() returns the number of milliseconds since the beginning of
// January 1, 1970 UTC.
// True, as the dates represent the same moment in time.
console.log(date1.getTime() == date2.getTime());
// False, as the dates are separate objects, though they happen to
// represent the same moment in time.
console.log(date1 == date2);
由於日期物件代表特定時間點,因此不需要跨時區「轉換」。而是以格式化為特定時區的字串。
如要以特定格式和時區將日期算繪為字串,請使用 Utilities.formatDate(date, timeZone, format)。例如:
const date = new Date