我正在努力解决以下公式的语法:
=IFS(OR(start="";end="");"";(end-start)*24<10;(end-start)*24-0.5;(end-start)*24>=10;(end-start)*24-1.0)
由于语法错误,Google 表格无法解析方程式。 ChatGPT 和其他 AI 没有帮助。这里有什么问题吗?
是否有任何工具可以测试 Google 表格公式?
假设
start
和 end
分别是一个单元格的 命名范围,使用简单的减法即可获得持续时间,如下所示:
=let(
duration, end - start,
workingHours, ifs(
isblank(start) + isblank(end), iferror(ø),
duration < "10:00", duration - "0:30",
true, duration - "1:00"
),
query(workingHours, "format Col1 '[h]:mm' ", 0)
)
如果没有命名范围,请将单元格位置添加到公式的开头,如下所示:
=let(
start, A2,
end, B2,
duration, end - start,
...
该公式将给出持续时间而不是“数字小时”。请参阅在 Google 表格中使用日期和时间值。
由于在 Google Sheets 中使用自定义公式有点麻烦,因此我求助于编写应用程序脚本来完成我需要的计算。这是脚本:
/**
* Calculates work duration in hours, accounting for break time.
* - work time >= 6h and work time < 9h --> 30 min break
* - work time >= 9h --> 45 min break
*
* @param {Date} start: the start date time.
* @param {Date} end: the end date time.
* @return {number} The duration in hours, accounting for break time.
*
* @customfunction
*/
const WORK_DURATION = (start, end) => {
// only calculate if start and end are given
if(!start || !end){
return
}
// get a javascript date object
const startDate = new Date(start);
const endDate = new Date(end);
// factor for conversion between h and ms
const hoursFactor = 1000 * 60 * 60;
// factor for conversion between min and ms
const minutesFactor = 1000 * 60;
// the raw duration in ms
let duration = (endDate.getTime() - startDate.getTime());
// reduce raw duration by 45 minutes if it is equal to or greater than 9h
if(duration>=9*hoursFactor){
return (duration - 45*minutesFactor) / hoursFactor;
}
// reduce raw duration by 30 minutes if it is equal to or greater than 6h and less than 9h
if(duration >= 6*hoursFactor && duration < 9*hoursFactor) {
return (duration - 30*minutesFactor) / hoursFactor;
}
// convert duration to h
return duration / hoursFactor;
};