首页 > 解决方案 > 如何通过迭代计算时间

问题描述

Google 脚本如何处理时间和日期。

如果您的工作表在单元格中输入了时间值(2:00、1:30 等,代表 2 小时和 1 小时 30),并且您想要遍历行,则将总数相加(因此上述结果为 3: 30); 你如何告诉谷歌脚本将它们添加在一起;当提到你所知道的时间时,你总是必须使用'new Date({INSERT CELL HERE})'吗?

我正在尝试让代码将所有时间值相加,如果超过 22.5 小时(22 小时 30 分钟 - 不是晚上 10 点)做点什么。

function ValidateForm(Action) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
var totalpaidovertime = 0.0;
var totalinlieutime = 0.0;
  var totalhours =  0.0; //new Date("January 01, 2019 00:00");
var validatedtotalhours = 0.0;
var validatedinlieuhours = 0.0;
var validatedtotalpaidovertime = 0.0;
var ui = SpreadsheetApp.getUi();
var hoursclaimed = sheet.getRange("F4:F35").getValues();

  if(spreadsheet.getActiveSheet().getName()=="Totals"){
    Browser.msgBox("Incorrect Sheet For This Action","Please select a users sheet to validate first and try again.",ui.ButtonSet.OK);
  }else{
    if (Action == "Check Overtime"){
      //get totalhours
      for (var r=0;r<=hoursclaimed.length;r++){
        if (hoursclaimed[r].getValue() !=""){
          totalhours+=hoursclaimed[r];       
        }
      }   
      Logger.log(sheet.getRange("f4").getValue()
      //calculate totalpaidovertime variable - 22.5 is 3 days of 7.5 work day.
      if(totalhours > 22.5) {
        totalpaidovertime = 22.5;
      }
      else {
        totalpaidovertime = totalhours;
      }
      //calculate totalinlieutime variable
      if(totalhours > 22.5) {
        totalinlieutime = totalhours - 22.5;
      }
      else {
        totalinlieutime = 0.0;
      }

      if (totalhours > 22.5) {
        Browser.msgBox("Total number of hours equals " + totalhours + " hours. Only 22.5 hours (3 days) will be added to Paid Overtime.");
      }

标签: javascriptdatetimegoogle-apps-scriptgoogle-sheets

解决方案


将电子表格中的持续时间传递到 Google Apps 脚本上的服务器端代码非常棘手,因为 Google 表格和 Google Apps 脚本/JavaScript 使用不同的 Epoch。好消息是我们可以使用getDisplayValue()getDisplayValues()并且在几个场景中更容易将持续时间作为文本值获取,然后首先将时间的每个部分解析为文本,然后将它们转换为数字。


推荐阅读