如何用Google Apps Script从Google Forms日期响应中提取月份
在Google Apps Script中提取日期月份以访问年月子文件夹
要提取Google表单提交日期中的月份,核心使用Date对象的getMonth()方法,结合getFullYear()可以得到完整的年月信息,用于定位对应子文件夹。
关键函数说明
getMonth():返回0-11的数字(一月对应0,十二月对应11),因此需要加1转换为1-12的实际月份。getFullYear():返回日期的四位年份,用于组合成YYYY-MM格式的文件夹名称。
完整实现示例
以下是表单提交触发的脚本,实现提取年月、定位/创建文件夹、移动上传文件的完整流程:
function onFormSubmit(e) { // 获取表单提交的会议日期(替换为你的表单日期字段名称) const dateInput = e.namedValues['会议日期'][0]; const meetingDate = new Date(dateInput); // 提取年份和转换为1-12的月份 const year = meetingDate.getFullYear(); const month = meetingDate.getMonth() + 1; // 格式化为YYYY-MM的文件夹名称(月份补两位,如5转为05) const yearMonthFolderName = `${year}-${String(month).padStart(2, '0')}`; // 访问根文件夹(替换为你的根文件夹ID) const rootFolder = DriveApp.getFolderById('你的根文件夹ID'); // 查找对应年月的子文件夹,不存在则创建 let targetFolder; try { targetFolder = rootFolder.getFoldersByName(yearMonthFolderName).next(); } catch (err) { targetFolder = rootFolder.createFolder(yearMonthFolderName); } // 移动表单上传的文件到目标文件夹(替换为你的文件上传字段名称) const uploadedFileIds = e.namedValues['会议文件']; uploadedFileIds.forEach(fileId => { const file = DriveApp.getFileById(fileId); file.moveTo(targetFolder); }); }
注意事项
- 确保表单的日期字段输入格式可被
new Date()正确解析,若用户输入非常规格式,需额外处理日期解析逻辑。 padStart(2, '0')用于将单个数字的月份转为两位(如5→05),保证文件夹名称格式统一。- 首次运行脚本时需授权,确保脚本拥有Drive文件的访问权限。
内容的提问来源于stack exchange,提问作者Carmen Noronha
相关产品推荐
相关产品推荐

