Google Apps Script计算日期差返回NaN问题,需实现文件自动删除
解决Google Apps Script计算日期差返回NaN的问题
问题原因
你得到NaN的核心原因是:modifiedDate和modifiedCreatedDate都是通过Utilities.formatDate生成的字符串类型(格式为dd-MM-yyyy),字符串之间无法直接进行减法运算,因此结果为NaN。
解决方案
直接使用原始的Date对象进行时间差计算,无需先将日期格式化为字符串。具体步骤:
- 保留
currentDate(当前日期的Date对象)和createdDate(文件创建日期的Date对象) - 计算两个日期的毫秒数差值,再转换为天数
- 根据天数判断是否删除创建时间距当前不超过4天的文件
修改后的代码如下:
function iterateFolder() { var folder = DriveApp.getFolderById('XXXXXXXXXXX'); console.log('Folder: ', folder.getName()); var files = folder.getFiles(); var currentDate = new Date(); // 取当前日期的当天起始时间,避免时分秒影响天数计算精度 var currentStart = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()); console.log('Now: ', Utilities.formatDate(currentStart, 'Australia/Adelaide', 'dd-MM-yyyy')); // 定义一天的毫秒数:24小时*60分钟*60秒*1000毫秒 const ONE_DAY_MS = 86400000; while(files.hasNext()){ var file = files.next(); var createdDate = file.getDateCreated(); // 取文件创建日期的当天起始时间 var createdStart = new Date(createdDate.getFullYear(), createdDate.getMonth(), createdDate.getDate()); console.log('File: ', file.getName(), ' Created On: ', Utilities.formatDate(createdStart, 'Australia/Adelaide', 'dd-MM-yyyy')); // 计算天数差:毫秒差除以一天的毫秒数,取整数部分 var dayDiff = Math.floor((currentStart - createdStart) / ONE_DAY_MS); console.log('Difference: ', dayDiff); // 判断是否删除:创建时间距当前不超过4天(<=4) if (dayDiff <= 4) { file.setTrashed(true); // 标记为删除(移到回收站) // 若需永久删除,需先启用Drive API,再调用 Drive.Files.remove(file.getId()) console.log('Deleted file: ', file.getName()); } } }
代码说明
- 基于
Date对象的原始时间戳(毫秒数)做减法,确保计算逻辑有效 - 转换为当天起始时间是为了避免时分秒差异导致的天数计算偏差(比如当前为10号23点,文件为7号1点,直接计算会得到3天多,取整为3天,但按日期跨度实际是4天)
- 删除文件的代码默认启用了移至回收站的逻辑,若需永久删除需额外配置Drive API权限
内容的提问来源于stack exchange,提问作者Vincy Benita
相关产品推荐
相关产品推荐

