我相信你的目标如下。
- 您希望使用带有 Google Apps 脚本的 Sheets API 将值放入 Google 电子表格。
- 在您当前的问题中,值包括日期对象。当使用
spreadsheets.values.update 方法放置此日期对象时,该值不能用作日期对象。您想解决此问题。
为了达到你的目的,把日期对象转换成其他的值怎么样?
模式一:
在此模式中,日期对象被转换为序列号并放入电子表格中。
const spreadsheetId = "###"; // Please set the Spreadsheet ID.
const values = [[new Date(), "b1", "c1"], [new Date(), "b2", "c2"]]; // This is a sample value for replicating your issue.
// Here, the date values are converted to the serial number.
const convertedValues = values.map(r => r.map(c => c instanceof Date ? (c.getTime() / 1000 / 86400) + 25569 : c));
Sheets.Spreadsheets.Values.update({values: convertedValues}, spreadsheetId, "Sheet1", {valueInputOption: "USER_ENTERED"});
-
(c.getTime() / 1000 / 86400) + 25569 用于从 unix 时间转换为序列号,引用自 this answer。
- 在此脚本中,日期对象作为序列号。因此,请将“A”列的数字格式设置为日期时间。这样,序列号就可以看作是日期时间。
模式2:
在此模式中,日期对象被转换为字符串值,以便解析为日期对象并放入电子表格中。
const spreadsheetId = "###"; // Please set the Spreadsheet ID.
const values = [[new Date(), "b1", "c1"], [new Date(), "b2", "c2"]]; // This is a sample value for replicating your issue.
// Here, the date values are converted to the string value for parsing as the date object.
const convertedValues = values.map(r => r.map(c => c instanceof Date ? Utilities.formatDate(c, Session.getScriptTimeZone(), "yyyy/MM/dd HH:mm:ss") : c));
Sheets.Spreadsheets.Values.update({values: convertedValues}, spreadsheetId, "Sheet1", {valueInputOption: "USER_ENTERED"});
- 在此脚本中,日期对象作为字符串值被
USER_ENTERED解析为日期对象。
- 此示例使用
yyyy/MM/dd HH:mm:ss 作为日期格式。当此格式无法解析时,请根据您的情况进行修改。
参考资料: