In this Salesforce tutorial, we will learn to develop a Salesforce application to calculate the business days or working days using Apex.
In addition, we will learn to create a Salesforce app, objects, and fields and also learn to add tabs to an application. Moreover, we will learn to create a Salesforce Apex Class and Apex Trigger.
While working as a Salesforce developer, one day I got a task to create an app that accurately calculates the business days. So, it will be helpful for project scheduling, lead time estimation, campaign arrangements, etc.
If you want to learn how to develop a Salesforce application using Apex to calculate business days in Salesforce Lightning with a proper step-by-step procedure and an example let’s deep dive through the article.
Understanding Salesforce Business Day Calculation Scenario
We are going to create a small application in Salesforce that calculates the business day. This application basically, determines the number of working days within a specific month while excluding weekends and national holidays.
Here, for understanding purpose, we are using an example of employees for whom we are going to calculate the number of working days or you can say business days within a specified month. We will exclude Saturdays, Sundays, and National Holidays in the USA from the original specified month days and calculate the business days.
Salesforce Application to Calculate Business Days using Apex
Here, are the step-by-step guidelines to create an application that calculates the working days in Salesforce using the Salesforce development framework Apex.
- Login to the Salesforce account. If you are not logged into the Lightning Experience, shift to it first.
- Go to the main home page of Salesforce Lightning Experience, if you are not in. For this, click on the “Gear” Icon in the top right corner and click on the “Setup” (Setup for the current app) option from the dropdown.

Step 1: Create Salesforce Custom Application
1: Search for “App Manager” in the “Quick Find” search box and click on it once you find it.

2: Click on the “New Lightning App” option in the top right corner of the Lightning Experience App Manager Setup.

3: Now you are directed “App Details & Branding” step. In the App Details section, enter your lightning app name and description. And in the App Branding section, if you want you can upload an image and choose the highlight color for its navigation bar. Then, click on the “Next” button.
Here, I entered an “App Name” as “Business Day Calculator” and once I clicked on the “Developer Name” it automatically filled up.

4: Once you click on the next, you will be directed to the “App Options” step. Simply click on “Next” without making a change to the prior settings.

5: In this step, you are on the “Utility Items (Desktop Only)” page. Again click on “Next” and move toward the next step.

6: After you click on the next, you are in the “Navigation Items” step. Here, you need to choose the items that you want to include in the app and arrange the order in which they appear. But till now, we don’t have an item that we want to include, so click on “Next” and proceed.

7: You’re on the “Users Profiles” step. Choose the user profiles that can access this app from the “Available Profiles” Tab and with the help of the arrows key shift the selected profile to the “Selected Profiles” Tab.
Here, I searched for the administrator in the search box of the available profile and clicked on “System Administrator”, then with the help of the “Add” arrow shifted it to the selected profiles.
8: To complete the process of the custom app creation for the business calculation in the salesforce lightning, click on the “Save & Finish” button.

With this, we have successfully created the custom app for the business day calculation. Now, we need some custom objects and fields, let’s learn to create them in the next step.
Step 2: Create Salesforce Custom Objects and Tabs
After creating an app, we need a database to store data in various columns. In Salesforce, the objects refer to the database table.
Also after creating objects, we need the user interface to add the records and view the records in the objects. In Salesforce, the tabs refer to the user interface that helps the user to enter and view the data in the fields of the object.
As per the above-defined scenario, we need to create two custom objects “Employee” and “National Holiday” with the tabs. A detailed description is given below:
Create Custom Object and Tab: Employee
We need an object named “Employee” that stores the information of the employee. Let’s see step by step how to create an object:
1: Click on the “Object Manager” in the top navigation bar.

2: Once you are directed to the object manager setup, click on the “Create” dropdown and choose the option “Custom Object”.

3: You are on the “Custom Object Definition Edit” step. In the “Custom Object Information” section, enter the singular and plural labels that are used in tabs.
Here, I entered the “Label” as “Employee” and the “Object Name” automatically filled up. Then, I entered the “Plural Label” as “Employees”.

4: Scroll down to the “Object Creation Options (Available only when custom object is first created)” option. Here, we have two options, click on the checkbox next to the second option “Launch New Custom Tab Wizard after saving this custom object”.
5: The rest of the setting of the custom object, remained as it is. Last, click on the “Save” button.

6: Once you click on the save button, you are on the “New Custom Object Tab” step. Select the tab style from the “Tab Style” lookup. After that, click the “Next” button.

7: After you click on next, you move to the “Add to Profiles” step. Simply click on the “Next” button and move to the proceeding step.

8: Now, you are in the “Add to Custom Apps” step. Choose the custom apps for which the new custom tab will be available. So, without making any changes I click on the “Save” button.

Create Custom Object and Tab: National Holiday
We also need one more object named “National Holiday” that stores the list of national holidays in the USA. Let’s see step by step how to create an object:
1: Again, click on the “Object Manager” in the top navigation bar.

2: Once you click on it, you are moved to the object manager setup, click on the “Create” dropdown and choose the option “Custom Object”.

3: Now, you will be on the “Custom Object Definition Edit” step. Enter the labels for the singular and plural that are used in the tabs in the “Custom Object Information” section.
Here, I typed “National Holiday” into the “Label” field. Then I typed “National Holidays” in the “Plural Label” field and the “Object Name” immediately filled up.

4: Move down to the “Object Creation Options (Available only when a custom object is first created)” section and there are two choices available here. Select the second one, “Launch New Custom Tab Wizard after saving this custom object”, by checking the box next to it.
5: Finally, click the “Save” button to finish the process of object creation and move to the process of tab creation.

6: The “New Custom Object Tab” step appears after you click the save button. From the “Tab Style” lookup, choose the desired tab style. Click the “Next” button after that.

7: You proceed to the “Add to Profiles” step after clicking next. Simply press the “Next” button to move to the next proceeding step.

8: In this step, you will be on the “Add to Custom Apps” step. Choose the custom apps for which the new custom tab will be available. Click the “Save” button without making any modifications.

With this, we have created objects in Salesforce Lightning. Next, we need fields in the objects that we have created let’s learn to create them in the next step.
Read Salesforce RIGHT Function
Step 3: Create Salesforce Custom Fields
After creating objects and tabs, we need columns in the database to store various records. In Salesforce, the fields are referenced to the database columns. As per the above-defined scenario, we need to create various fields in the respective objects. A detailed description is given below:
Create Custom Fields within the Employee object
We now need various fields in the Salesforce Employee object to store information such as name, a month whose working day you want to check, and the number of working days of the respective employee within the respective fields “Name”, “Month” and “Working Days”.
Let’s see step by step how to create each field in the object:
1: If you are not in the object manager, click on the “Object Manager” in the top navigation bar.

2: In the “Quick Find” search bar search for the newly created custom object “Employee”, Once you find it click on it.

3: Click on the “Fields & Relationships” option on the left side of the page. After that, you are directed to the fields and relationship page setup, click on the “New” button on the top right side.

Note: When you create a new custom object “Employee”, it gets created with the standard field “Employee Name”. So, we don’t need to create the employee name field again.
Create Custom Field Month
4: Once you click on the new button, you are directed to the step “Choose the field type”. Specify the type of information that you want to store in the custom field. As I want to create a field that stores months, I decided to choose the picklist as a data type. Click on the radio button next to the “Picklist” data type and then click on “Next”.

5: You are in the “Enter the details” step. Enter the “Field Label” and the “Field Name” will automatically fill up. Here, I entered the field label “Month”.
6: Set up the “Values” that you want to show in the picklist field. Here, you have two options either you can use the global picklist value set if you have one, otherwise, you can go with the next option “Enter values, with each value separated by a new line”.
I chose the second option by clicking on the radio button next to it and entered the names of the month in the box populated below such as January, February, March, etc. Then, click on the “Next” button.

7: After clicking on the next, you are directed to the “Establish field-level security” step. Choose the profiles to which you want to grant edit access to this field, some of the profiles are already selected. Simply click on the “Next” button.

8: You are now on the “Add to page layout” step. Select the page layouts that should include this field, by default all the page layout names are selected. So, I click on the “Save & New” button as I want to finish this process and create one more custom field.

Create Custom Field Working Day
We also need one more field named “Working Day” that stores the number of working days in the specified month. Let’s see step by step how to create a field.
While creating the previous field, at last, we clicked on the save and new button. So, it again directed you to the “Choose the field type” step.
1: In this step, select the kind of data you want to save in this custom field. I want to choose the number as a data type because I want to create a column that stores the number of working days. To select the “Number” data type, click on the radio button next to it, and then click “Next”.

2: Once you click the next, you will be directed to the “Enter the details” step. Now, enter the “Field Label” and the “Field Name” will get automatically filled. In this case, I type the field label as “Working Day”.
3: Now set the length of the number i.e. number of digits to the left of the decimal points and the decimal places. Here, I set the “Length” as 17 and “Decimal Places” to 1. After that, click on the “Next” button.

4: You are on the “Establish field-level security” step. Some of the profiles are already selected, so pick the profiles to which you wish to allow edit access to this field. After that, click “Next”.

5: Once you click on the next, you will be directed to the “Add to page layout” step. Here, you have to choose the page layouts that should have this custom field and by default, all the page layout names are selected. So, directly click on the “Save” button to finish this process.

Create Custom Fields within the National Holiday object
We also need various fields in the Salesforce National Holiday object to store the information such as the name of the holiday in the USA and the date of the holiday within the respective fields “National Holiday Name” and “Date”.
Let’s see step by step how to create each field in the object:
1: Click on “Object Manager” in the top navigation bar if you aren’t already there.

2: Search for the custom object “National Holiday” in the “Quick Find” search bar, and then click it.

3: On the left side of the page, select “Fields & Relationships”. Once you are on the fields and relationship page setup, click the “New” button in the upper right corner.

Note: The default field “National Holiday Name” is added when a new custom object named “National Holiday” is created. The national holiday name field doesn’t need to be created again.
Create Custom Field Date
4: After clicking the new button, you are taken to the step “Choose the field type”. Select the kind of data you want to save in the custom field. I want to store the date of the national holiday, so I need to choose “Date” as the data type by clicking on the radio button next to it. Then, click on “Next”.

5: Now, you are in the “Enter the details” step. Enter the “Field Label” and the “Field Name” will automatically populate. Here, I entered the field label as “Date” and clicked on the “Next” button.

6: After clicking the next button, you are taken to the “Establish field-level security” step. Select the profiles to which you wish to allow edit access to this field. Some fields are already selected, so without selecting any other profile, I clicked on the “Next” button.

7: You are at the “Add to page layout” step. Select the page layout that should include this field and by default, all the page layout names are selected. So, I click on the “Save” button to finish the process of creating a field in the national holiday object.

With this, we have created custom fields in their respective objects and tabs in Salesforce Lightning. Next, we need to add the above-created custom tabs for the custom objects to the application.
Step 4: Add Salesforce Custom Tabs to App
We also need to add tabs to the specific Salesforce app to efficiently store, access, and manage records for the objects related to the app. Basically, it is done to improve the user experience and make it easy for the user to find the objects or records.
Let’s see step by step how to add custom tabs to the Salesforce application:
1: Click on the “Gear” Icon in the top right corner and then click on the “Setup” (Setup for the current app) option from the dropdown.

2: On the left side page, in the “Quick Find” box, search for the “App Manager” and once it is found click on it.

3: Once you click on it, you will see the list of all the Salesforce apps either custom or standard. From the app list, search for the app that we have created above named “Business Day Calculator”.
4: Click on the dropdown arrow given at the end of the application. From here, click on the “Edit” option to edit the application.

5: You will see the five different options given in the “App Settings” section. From here, select the “Navigation Items” option.
6: Choose the items from the “Available Items” columns to include in the app by shifting the selected items to the “Selected Items” columns by clicking on the arrows, and arranging them in the order in which they appear.
Here, I searched for the “Employee” and “National Holiday” in the “Available Items” and transferred them to the “Selected Items”.
7: Finally, click on the “Save” button to complete the process of adding tabs to the application.

With this, we have successfully added the custom tabs of the objects to the application navigation bar. Now, we need to create the Salesforce Apex Class in the next step.
Step 5: Create Salesforce Apex Class
We also need to define Salesforce Apex Class that is we need to define the custom business logic to calculate the business number excluding Saturdays, Sundays, and National Holidays using the Apex programming language.
Let’s see step by step how to define the Salesforce Apex Class:
1: Move back to the main home page setup, search for the “Apex Classes” in the “Quick Find” box, and once you find it click on it.

2: Once you click, the “Apex Classes” page is opened where you can add the apex code which is an object-oriented programming language that allows developers to develop on-demand business applications on the Lightning Platform. Then, click on the “Developer Console” button.

3: Once you click, the new developer console window will open. Click on the “File” dropdown located at the top navigation of the page.
4: From the dropdown, click on the “New” dropdown, and from here click on the “Apex Class”.

5: In this step, it will open the pop window “New Apex Class”. Please enter a name for your new “Apex Class” and then click on the “OK” button. Here, I entered the apex class name “BusinessDayCalculation”.

6: Once you click OK, it will open up the developer console code box, where you add your apex class code that calculates the business days.
7: Enter the code to create an apex class. Here, below is the code that I have created for calculating the business days without Saturdays, Sundays, and USA National Holidays within a specified month of the specific employee.
public class BusinessDayCalculation {
public static void calculateAndUpdateWorkingDays(List<Employee__c> employees) {
Map<Integer, Set<Date>> holidaysMap = new Map<Integer, Set<Date>>();
for (National_Holiday__c currHoliday : [SELECT Date__c FROM National_Holiday__c]) {
Integer holidayMonth = currHoliday.Date__c.month();
if (!holidaysMap.containsKey(holidayMonth)) {
holidaysMap.put(holidayMonth, new Set<Date>());
}
holidaysMap.get(holidayMonth).add(currHoliday.Date__c);
}
for (Employee__c emp : employees) {
String selectedMonth = emp.Month__c;
if (selectedMonth != null) {
Integer year = Date.today().year(); // Assuming the year is not needed in the picklist
Integer month = getMonthNumber(selectedMonth);
Date startDate = Date.newInstance(year, month, 1);
Date endDate = startDate.addMonths(1).addDays(-1);
Set<Date> holidaysSet = holidaysMap.containsKey(startDate.month()) ?
holidaysMap.get(startDate.month()) : new Set<Date>();
Integer workingDays = 0;
for (Date dt = startDate; dt <= endDate; dt = dt.addDays(1)) {
DateTime currDate = DateTime.newInstance(dt.year(), dt.month(), dt.day());
String todayDay = currDate.format('EEEE');
if (todayDay != 'Saturday' && todayDay != 'Sunday' && !holidaysSet.contains(dt)) {
workingDays++;
}
}
// Update the field without DML
emp.Working_Day__c = workingDays;
}
}
}
public static Integer getMonthNumber(String monthName) {
monthName = monthName.toLowerCase();
Map<String, Integer> monthMap = new Map<String, Integer>{
'january' => 1, 'february' => 2, 'march' => 3, 'april' => 4, 'may' => 5, 'june' => 6,
'july' => 7, 'august' => 8, 'september' => 9, 'october' => 10, 'november' => 11, 'december' => 12
};
return monthMap.containsKey(monthName) ? monthMap.get(monthName) : 1; // Default to January if not found
}
}
A line-by-line explanation of the code:
- We create a public class named “BusinessDayCalculation” in the apex within the public static method “calculateAndUpdateWorkingDays” which takes the list of custom “Employee__c” object as a parameter.
- Create an empty map named “holidaysMap” where keys are taken as integers that represent the months, values are taken as sets of days related to the months.
- The for loop is used to fetch the list of holidays from the custom objects “National_Holiday__c”, especially the “Date__c” field. And for each national holiday in the USA, it fetches the month using the month() function on the date.
- The if function is used to check if the “holidaysMap” does not already have the key for that month, if not It adds an entry with an empty set for the holiday’s month. Then, it inserts the date of the present holiday into the set belonging to that holiday month in the “holidaysMap”.
- The for loop iterates over to the list of the custom objects “Employee__c” that is passed to the loop as an argument and it gets the current employee’s value for the custom “Month__c” field.
- The if function is used to check the valid month was selected for the employee in the “selectedMonth”, if it is:
- It uses the “Date.today().year()” to get the current year and then converts the selected month name into an integer value using the “getMonthNumber” method.
- Then the “startDate” and “endDate” for the chosen month are then calculated. “endDate” is set to the last day of the chosen month by adding one month and taking away one day from and “startDate”, which is set to the first day of the chosen month.
- After that, we get the list of holidays from the “holidaysMap” for the month of the “startDate” and initialize an empty set if that month has no holidays.
- The for loop iterates through each day in the date range of the given month. It builds a “DateTime” object from the “Date” object for each day to obtain the day of the week using the “EEEE” format, which provides the day’s entire name.
- The if function is used to determine if the day is not a Saturday, Sunday, or holiday. The “workingDays” counter is increased.
- After that, determine the number of working days for the given month and update the custom “Working_Day__c” field of the current employee.
- Next, the month name is converted to lowercase when sent as input to the “getMonthNumber” method. After that, it maps month names to the associated integer values using a prepared map called “monthMap”.
- Last, we return the appropriate integer if the provided “monthName” is present in the map, otherwise, it defaults to returning 1 (January).

8: After entering the code, click on the “File” option in the top navigation, and from here click on the “Save” button to successfully save the code of the apex class.

With this, we have successfully created an apex code in Salesforce to calculate the working days. Now, we need to create the Salesforce Apex Trigger in the next step.
Step 6: Create Salesforce Apex Trigger
We also need to define the Salesforce Apex Trigger that executes according to the response of Salesforce events. Basically, this apex trigger is used to automate the process of working day calculations when records are created, updated, or deleted.
Let’s see step by step how to define the Salesforce Apex Trigger:
1: You are already on the Salesforce developer console window. Click on the “File” drop-down that appears in the page’s top navigation. Then, click on “New” and after that click on the “Apex Trigger” option.

2: It will open the “New Apex Trigger” pop-up. Please enter a name for your new Apex Trigger in the “Name” box and choose the “sobject” from the dropdown field.
Here, I enter the trigger name “EmployeeTrigger” and choose “Employee” as the sobject as I want to create this trigger on the employee object. It means it works when we enter, update, or delete any record in the employee object.
3: Click on the “Submit” button to open up the developer console code box, where you add your apex trigger code that works upon response to a specific event.

4: Enter the code to create an apex trigger. Here, below is the code that I have created to perform the action on the creation, updation, or deletion of an employee record.
trigger EmployeeTrigger on Employee__c (before insert, before update) {
List<Employee__c> employeesToUpdate = new List<Employee__c>();
for (Employee__c emp : Trigger.new) {
if (Trigger.isInsert || (Trigger.isUpdate && emp.Month__c != Trigger.oldMap.get(emp.Id).Month__c)) {
employeesToUpdate.add(emp);
}
}
if (!employeesToUpdate.isEmpty()) {
BusinessDayCalculation.calculateAndUpdateWorkingDays(employeesToUpdate);
}
}
A line-by-line explanation of the code:
- We create a trigger named “EmployeeTrigger” that works on the “Employee__c” custom object. And this trigger should execute before records are created or updated.
- We create a list named “employeeToUpdate” that stores the “Employee__c” records that need to update.
- The for loop iterates over the “Employee__c” record with respect to the “Trigger.new” variable. This “Trigger.new” stores the new version of the inserted or updated records.
- The if function is used to check whether the trigger is filtered out due to an insert operation or filtered out due to an update and the “Month__c” field of the “Employee__c” record and different from the old value. If it is, the “Employee__c” record is inserted into the “employeesToUpdate” list.
- The if function is again used to check if the “employeesToUpdate” list has any records. If it is, the static method “calculateAndUpdateWorkingDays” from the “BusinessDayCalculation” class takes an “employeesToUpdate” list as an argument do calculation related to the working days, and update the records according to the result.

5: After entering the code, select “File” from the top navigation, and then click the “Save” button to complete the saving process of the apex trigger code.

With this, we have successfully added the Salesforce Apex Trigger code and completed the process of the business day calculation in Salesforce. Now, we need to check how your application works.
Step 7: Test Salesforce Calculate Working Day Application
After completion of the Salesforce application that calculates the business day within the specific month of an employee by excluding the weekends and national holidays in the USA. It’s time to test the application and see how it works and shows the result.
Here are the steps to test our Salesforce application:
- Click on the “Gear” Icon in the top right corner and then click on the “Setup” (Setup for the current app) option from the dropdown.
- Click on the “App Launcher” and search for the application “Business Day Calculator”, Once you found it, click on it.

Insert National Holiday Records
1: Click on the “National Holidays” tab located at the top navigation bar.
2: Click on the “New” button at the top right of the page to enter a new record of a national holiday in the USA.
3: Once you click on new, the “New National Holiday” popup is opened. Enter the “National Holiday Name” and choose the “Date” of the holiday in the USA.
4: Then, click on the “Save & New” button to save the record and again start the process of entering the new national holiday record.

Note: Repeat this “Save & New” step till all the national holidays in the USA are inserted.
With this, we have learned to add the record in the Salesforce National Holiday object. Now we will learn to add the record in the Salesforce Employee object.
Insert Employee Records
1: Click on the “Employees” tab located at the top navigation bar.
2: Click on the “New” button at the top right of the page to enter a new record of an employee.
3: Once you click, the “New Employee” popup is opened. Enter the “Employee Name” and choose “Month” from the dropdown whose working day you want to see.
Note: Leave the “Working Days” field blank, it will be automatically filled up when you save the record.
4: Click on the “Save” button to save the employee record.

With this, we have learned to add the record in the Salesforce Employee object. Now, let’s check the result or working day of an employee.
Check the Result
Here are the steps to check the results of the application i.e. number of business or working days of an employee within a specific month:
1: Choose any specific employee from the list of employees. Here, I choose “David Daniel”.
2: In the detail section, you can see that the working day is successfully counted for the month of “March”. I show that the employee working days is 23.0. Let’s verify whether it counts correctly or not.
In the month of “March” of the year 2023, there is a total of 31 days out of which there are 4 Saturdays, 4 Sundays, and 0 National Holidays in the USA. It means there are a total of 8 nonworking days in the month of March.
To count the total number of business days in the March month we need to subtract nonworking days from the working days i.e. 31-8 which results in 23. It means, the code successfully calculated the business days.

3: Let’s try to change the month by clicking on the pencil choosing the new month and saving the employee. Here, I change the month from “March” to the “July”.
4: You can see that, it shows the number of business days of an employee for the month of “July” is 20. Let’s verify this also. In the month of July, there are a total of 31 days out of which there are 5 Saturdays, 5 Sundays, and 1 National Holiday in the USA.
It means there are a total of 11 non-working days in the month of July. To calculate the working days subtract 11 from the 31 and we get the result as 20. This means the apex code is working correctly.

With this, we have successfully learned to create and test an application in Salesforce that calculates the business day of the employee within a specific month excluding weekends and national holidays using the Salesforce developer programming language Apex.
Conclusion
With this, we have learned to create a Salesforce application using the Salesforce developer framework language Apex to calculate the business days.
We also learned the process of creating custom objects with fields in a custom application, an apex class, trigger coding to calculate the working days in a specified month, and last but not least to apply this concept within a practical example.
You may like to read the following topics:
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.