【问题标题】:Open file using a file name based on the current date使用基于当前日期的文件名打开文件
【发布时间】:2016-01-04 14:21:43
【问题描述】:

我有一个按名称打开文件的脚本,但该文件每天都会用新名称更新。例如,文件名可能是“L661_CAD-04-01-16.csv”,但第二天可能会更改为“L661_CAD-05-01-16.csv” '。

我希望名称的第一部分与 L661_CAD- 相同,并在脚本中更新日期,以便查看最新文件。

这是我正在使用的当前代码,它会查找完整的文件名:

var fSource = DriveApp.getFolderById('0B2lVvlNIDosoajRRMUwySVBPNVE'); // reports_folder_id = id of folder where csv reports are saved
var fi = fSource.getFilesByName('L661_BOM-CAD_14-12-15.csv'); // latest report file

【问题讨论】:

    标签: google-apps-script google-drive-api google-apps


    【解决方案1】:

    有很多方法可以实现这一点 - 任何可以从 Date 对象中获取日、月和年的方法都可以使用。

    这是一个基于 Google Apps 脚本Utilities.formatDate 方法的单行代码:

    var filename = Utilities.formatDate(new Date(),
                                        Session.getScriptTimeZone(),
                                        "'L661_BOM-CAD_'dd-MM-yy'.csv'");
    

    如果你想用它来获取任意日期的文件,你可以在第一个参数中提供目标日期。

    如果你想改用“纯 JavaScript”,你可以这样做:

    var today = new Date()
    var day = today.getDay();
    if (day < 10) day = '0'+day;
    var month = today.getMonth() + 1;
    if (month < 10) month = '0'+month;
    var year = today.getFullYear().toString().substr(2,2);
    
    var filename = 'L661_BOM-CAD_%dd%-%mm%-%yy%.csv'
                   .replace('%dd%',day)
                   .replace('%mm%',month)
                   .replace('%yy%',year);
    

    对于任何想要调整它以满足他们特定需求的人来说,还有很多其他的 formatting dates in JavaScript, 示例。

    【讨论】:

    • 感谢您的回复。我找到了上面提到的解决方案。
    【解决方案2】:

    找到解决方案,希望这可以帮助某人

    var date= Utilities.formatDate(new Date(), "GMT", "dd-MM-yy");
    var fi = fSource.getFilesByName('*first part of the file name*'+ date +'.csv'); // L661_bom-cad is the first part of the file name
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多