You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Apps Script中动态筛选修改时间晚于昨日的文件?

解决Drive文件修改时间动态筛选问题

你的问题出在直接将Date对象拼接进搜索字符串,Drive的searchFiles方法要求日期必须是符合RFC 3339标准的字符串格式,而直接拼接Date对象会生成类似Wed Sep 20 2023 10:00:00 GMT+0800 (中国标准时间)的非标准格式,导致筛选逻辑失效。

修正方案

使用Utilities.formatDate方法将Date对象转换为Drive支持的日期格式,代码修改如下:

const MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
const now = new Date();
const yesterday = new Date(now.getTime() - MILLIS_PER_DAY);
// 转换为Drive搜索支持的日期格式(RFC3339)
const formattedYesterday = Utilities.formatDate(yesterday, Session.getScriptTimeZone(), "yyyy-MM-dd'T'HH:mm:ss'Z'");

function extractStudentIDsAndSectionToSheets(){
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const folder = DriveApp.getFolderById(FOLDER_ID);
  // 使用格式化后的日期字符串
  const files = DriveApp.searchFiles('title contains "stuff" and mimeType = "application/pdf" and modifiedDate > "' + formattedYesterday + '" and trashed=false');

  let allIDsAndCRNs = []
  //Iterate through each folder
  while(files.hasNext()){
    let file = files.next();
    let fileID = file.getId();

    // 剩余代码...
  }
}

关键说明

  • Utilities.formatDate的三个参数分别是:要格式化的Date对象、时区(用Session.getScriptTimeZone()获取脚本时区,避免时区偏差)、目标格式字符串。
  • 格式"yyyy-MM-dd'T'HH:mm:ss'Z'"是Drive搜索明确支持的RFC3339格式,能准确匹配文件的修改时间。
  • 如果需要筛选“昨日0点至今”的文件,也可以调整日期计算,比如把yesterday设置为当天0点减去一天:
    const yesterdayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
    const formattedYesterdayStart = Utilities.formatDate(yesterdayStart, Session.getScriptTimeZone(), "yyyy-MM-dd'T'HH:mm:ss'Z'");
    

内容的提问来源于stack exchange,提问作者Whoopcg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 03:31:12