不明白简单代码中的这个错误

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

因此,我尝试在 Goggle Apps 脚本中编写一段代码,该代码将自动创建一个新的 google 电子表格,其中包含基于当前日期 + 2 周的名称和日期,但我不断收到此错误

异常:参数 ((class),null) 与 Utilities.formatDate 的方法签名不匹配。

我不明白为什么会发生这种情况。正如您所看到的,我有几个点,控制台验证 dateToFormat 变量是一个对象并且正常运行,但是一旦它进入 var formattedDate 行,它就会中断。这是代码:

`function createNewSheetWithDate() {
// Get the active spreadsheet
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();

// Get today's date and add two weeks
var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 14);

// Format the date (optional, customize the format as needed)
console.log(typeof currentDate);

var dateToFormat = new Date(currentDate.getTime());

console.log(typeof dateToFormat);
console.log(dateToFormat.getFullYear());
console.log(dateToFormat);

var formattedDate = Utilities.formatDate(dateToFormat, null);


// Create the new sheet name with the formatted date
var newSheetName = "Inventory - " + formattedDate;

// Insert a new sheet and set its name
var newSheet = spreadsheet.insertSheet(newSheetName);
}`

我已经尝试了我能想到的一切来解决这个问题,但我在编程/编码方面并不是很先进,所以也许只是一些我不知道的简单事情

google-apps-script
1个回答
0
投票

您没有指定时区或日期格式。

改变

var formattedDate = Utilities.formatDate(dateToFormat, null);

到(或者任何你想要的样子)

var formattedDate = Utilities.formatDate(dateToFormat, "GMT", "MM-dd-yyyy");
© www.soinside.com 2019 - 2024. All rights reserved.