Hi everyone,
Following our Zoho Creator - Tips and Tricks series every fortnight, we are back today with a tip based on one of the most asked questions in the forum. That's right. This tip would help you calculate the business days between two dates excluding the weekend.
For example, if wish to know the number of working days in a particular month, you need to write a custom function to do this calculation.
Functions are nothing but a unit of code written to perform a specific task.
Let's see how to do this:
- // Here WorkDays is the name of the function.
- int WorkDays(date start_date, date end_date)
- {
- //total_days will store the value of numbers of days between start date and end date.
- total_days=(days360(input.start_date,input.end_date) +1);
- counter=leftpad("1",total_days).replaceAll(" ","1,").toList();
- //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.
- week_ends=0;
- date_counter=input.start_date;
- for each index n in counter
- {
- //Use getDayOfWeek() to identify if it is a weekday or weekend.
- if((date_counter.getDayOfWeek() == 1) || (date_counter.getDayOfWeek() == 7))
- {
- week_ends=(week_ends + 1);
- }
- //Now add one day for the next loop
- date_counter=date_counter.addDay(1);}
- total_business_days=(total_days - week_ends);
- return total_business_days;
- }
Let's look at some of the built-in functions that we used in the above code:
days360 is a built-in function that returns the number of days between two given dates.
getDayOfWeek is a built-in function to get the day of the week corresponding to a date. It will return a number range from 1 to 7. The number 1 represents a Sunday, 2 represents a Monday and so on.
replaceAll is a built-in function that helps you replace all the occurrence of a particular substring in a sting.
toList is a built-in function that removes the given separator in a string, and replaces it with a comma.
Isn't it easy? Give it a try. If you have any doubts or queries regarding this tip, please feel free to add them as comments below. We would be happy to address them all.