Google 脚本如何处理时间和日期。
如果您的工作表在单元格中输入了时间值(2:00、1:30 等,代表 2 小时和 1 小时 30)并且您想要遍历行,将总数加起来(因此上面的结果3 点 30 分);你如何告诉谷歌脚本将它们加在一起;当提到您知道的时间时,您是否总是必须使用“新日期({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.");
}
最佳答案
将持续时间从电子表格传递到 Google Apps 脚本上的服务器端代码很棘手,因为 Google 表格和 Google Apps 脚本/JavaScript 使用不同的纪元。好消息是,我们可以使用 getDisplayValue()
和 getDisplayValues()
,在某些情况下,它们可以更轻松地获取持续时间作为文本值,然后解析时间的每个部分首先作为文本,然后将它们转换为数字。
关于javascript - 如何通过迭代计算时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56756166/