【问题标题】:Run custom function if value in cell is date如果单元格中的值为日期,则运行自定义函数
【发布时间】:2013-03-11 19:46:07
【问题描述】:

我是 Google 脚本的新手。我想检查单元格中的值是否为日期,如果是,则更改日期的默认格式,然后返回新的格式化日期值。

这是我想要的示例:

var activeCellValues = SpreadsheetApp.getActiveRange().getValues();
if ( activeCellValues = "Is_Type_Date")
       {   
          var activeCellValues = Utilities.formatDate(pubDateCell,"PST", "MM/dd/yyyy")
       }

这可能吗?

【问题讨论】:

    标签: google-apps-script google-sheets


    【解决方案1】:

    使用下面的isDate() 函数来完成您的要求。可以更改日期格式以满足其他需要。请参阅 [Utilities.formatDate()][3] 了解更多信息。

    // From http://stackoverflow.com/questions/1353684
    // Returns 'true' if variable d is a date object.
    function isValidDate(d) {
      if ( Object.prototype.toString.call(d) !== "[object Date]" )
        return false;
      return !isNaN(d.getTime());
    }
    
    // Test if value is a date and if so format
    // otherwise, reflect input variable back as-is. 
    function isDate(sDate) {
      if (isValidDate(sDate)) {
        sDate = Utilities.formatDate(new Date(sDate), "PST", "MM/dd/yyyy");
      }
      return sDate;
    }
    

    在您的脚本中,您使用了Range.getValues() 函数,该函数将返回给定范围内数据的二维数组。 (在您的情况下,您的整个工作表。)因此,您需要遍历读取的值并在您感兴趣的任何单元格上调用此函数,然后将信息写回电子表格。在 Google 的文档和 Stackoverflow 上都有很多这样的例子。

    【讨论】:

    • isValidDate 仍然是测试值是否为 Date 对象的最简单方法吗? Apps Script 现在有用于此目的的内置函数吗?
    猜你喜欢
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多