技巧6:如何计算两个日期之间的工作日。

技巧6:如何计算两个日期之间的工作日。

原文链接:https://help.zoho.com/portal/en/community/topic/tip-06-how-to-calculate-the-business-days-between-two-dates



嗨,大家好,


每两个星期跟随我们的Zoho Creator-技巧和窍门系列,今天我们回来了,该技巧基于论坛中最常见的问题之一。那就对了。本技巧将帮助您计算两个日期之间的工作日(周末除外)。

例如,如果希望知道特定月份的工作天数,则需要编写一个自定义函数来进行此计算。

函数不过是为执行特定任务而编写的代码单元。


让我们看看如何做到这一点:


  1. // Here WorkDays is the name of the function.
  2. int WorkDays(date start_date, date end_date)
  3. {
  4. //total_days will store the value of numbers of days between start date and end date.
  5. total_days=(days360(input.start_date,input.end_date) +1);
  6. counter=leftpad("1",total_days).replaceAll(" ","1,").toList();
  7. //Here counter will generate a list like {1,1,1,1,1,1} with number of 1's based on value returned in total_days.
  8. week_ends=0;
  9. date_counter=input.start_date;
  10. for each index n in counter
  11. {
  12. //Use getDayOfWeek() to identify if it is a weekday or weekend. 
  13. if((date_counter.getDayOfWeek() == 1) || (date_counter.getDayOfWeek() == 7))
  14. {
  15. week_ends=(week_ends + 1)
  16. }
  17. //Now add one day for the next loop
  18.  date_counter=date_counter.addDay(1);}
  19. total_business_days=(total_days - week_ends);
  20. return total_business_days;

 

让我们看一下上面代码中使用的一些内置函数:

days360是一个内置函数,它返回两个给定日期之间的天数。


getDayOfWeek是一个内置函数,用于获取与日期相对应的星期几。它将返回从1到7的数字范围。数字1代表星期日,2代表星期一,依此类推。

replaceAll是一个内置函数,可帮助您替换字符串中所有出现的特定子字符串。


toList是一个内置函数,该函数删除字符串中给定的分隔符,并将其替换为逗号。

容易吗?试试看。如果您对此技巧有任何疑问或疑问,请随时在下面添加它们作为评论。我们很乐意解决所有这些问题。