javascript - 如何通过迭代计算时间
问题描述
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.");
}
解决方案
将电子表格中的持续时间传递到 Google Apps 脚本上的服务器端代码非常棘手,因为 Google 表格和 Google Apps 脚本/JavaScript 使用不同的 Epoch。好消息是我们可以使用getDisplayValue()
,getDisplayValues()
并且在几个场景中更容易将持续时间作为文本值获取,然后首先将时间的每个部分解析为文本,然后将它们转换为数字。
推荐阅读
- jmeter - 使用 Amazon ECS 进行 Jmeter 远程测试
- c - 如何从接收方向发送方发送 NACK 消息
- android - AndroidViewModel 实例化而不传递应用程序上下文?
- c++ - 调用数组内部的结构
- python - 如何将这部分代码提取到一些可重用的方法中?
- angular - 如何从左到右显示 mat-list-items
- javascript - 如何将查询字符串数据传递到我网站的所有页面?
- c - 初始化结构后 C 中的分段错误
- java - 带有 Switch Case 和数组的顺序和二进制 Java 程序。输出不正确。程序没有错误
- java - 如何从 Java 访问 Gradle 额外属性?