【问题标题】:Getting an error parsing data in google sheet custom script function在 google sheet 自定义脚本函数中解析数据时出错
【发布时间】:2019-06-03 19:12:18
【问题描述】:

我创建了一个简单的自定义函数来测试 google sheet 脚本函数。函数定义为:

/**
* convert duration such as 1:30 to 1.5
 *
 * @customfunction
 */
function SIMPLETEST(input) {
  // simply return the input for now to test.
  return input;

}

在我的电子表格中,我有一个单元格 A2,其值为 3:30:00。当我在 B2 上应用此函数时,例如将 b2 设置为:=DURATION_DECIMAL(A2) 它返回12/30/1899,我认为这是基准日期。

为什么会这样?

【问题讨论】:

    标签: google-apps-script google-sheets custom-function


    【解决方案1】:

    这是因为您必须将该单元格的数据类型设置为“自动”或“持续时间”,Google 表格会猜测“3:30:00”是自动的日期/时间类型,持续时间它将其转换为日期/时间以传递给您的函数。它可以让您保持格式 (#:##:##),但是当您将其传递给自定义公式时,Sheets 首先将其转换为 Javascript Date 对象,然后您的函数会返回该对象,并且工作表会自动显示为常规日期 (12/30/1899)。请参阅 Google 关于使用自定义函数进行日期转换的警告here

    最简单的解决方案是使用格式选择下拉菜单将您的输入格式显式设置为“纯文本”,然后在您的自定义函数代码中,您可以根据需要对其进行解析。

    例如,我使用this StackOverflow 的答案来编写您的自定义函数:

    function DURATION_DECIMALS(input){
      // https://stackoverflow.com/a/22820471/11447682
      var arr = input.split(':');
      var dec = parseInt((arr[1]/6)*10, 10);
      return parseFloat(parseInt(arr[0], 10) + '.' + (dec<10?'0':'') + dec);
    }
    

    这里它使用设置为纯文本的格式:

    【讨论】:

      【解决方案2】:

      这对我有用:

      function durdechrs(dt) {
        return Number((dt.valueOf()-new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf())/3600000).toFixed(2);
      }
      

      【讨论】:

        猜你喜欢
        • 2015-06-09
        • 1970-01-01
        • 1970-01-01
        • 2019-11-12
        • 1970-01-01
        • 1970-01-01
        • 2022-11-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多