Calculate the Working Days Between Two Given Days in C#


Introduction:

In this article we will discuss how to calculate the number of working days between the two given days in C#.

Creating a Windows Form Application:

Start the Visual Studio 2010; create a Windows Form Application and name it as CalculatingNoOfDays.

1.gif

Designing the Form:

Place the following controls

  • Three Labels
  • Two DateTimePicker
  • One Button

Give the proper names for controls and set the Text property of labels as shown below. After designing the form looks like the following.
2.gif

Functionality Explanation:

The main aspect of this article is to calculate the number of working days between the given two days.

For example if one organization needs to take the list of employee's actual working days. In this situation they need to omit the weekend holidays as well as the organization's holidays. For that situation, this bit of code will be useful I guess. So for sample, here we are having an array of DateTime which will have the organizations holiday list.

3.gif

In this example the listOfOrgHolidays array has two dates which are falling on the day Wednesday and Monday respectively. Even though these two days are falling on working days it is in the organization's holiday list so we need to omit from working days.

CalculateDays Method:

This is the method to calculate the number of working days for an organization. The screenshot below shows the code.

4.gif

For this method we are passing the start and end days to calculate the number of working days.

5.gif

The above bit of code is to check whether the end date is greater than the start date or not.

6.gif

In this loop we are checking the holidays and counting the number of working days.

7.gif

Here the LINQ has been used to check the holidays in the organization's holidays list. If the organization's holiday date is between the start and end date then the LINQ will return the string holidays.

One of the major methods here is DateTime.Compare(). This method is used to compare the two given dates.

Finally in the Button event we are calling the CalculateDays() method to calculate the number of working days.

If you run this project the final windows form will be like this as our given sample input.

Up Next
    Ebook Download
    View all
    Learn
    View all