Click here to Skip to main content
16,011,949 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi

I have two calendar controls one for From and the other for To and from the two dates selected i have to calculate the number of days and also i have to exclude the saturdays and sundays (i.e) if i have applied for leave from friday till monday I have to exclude sat and sunday and calculate the leave as 2 how to do it
Posted

Write an extension method to exclude the weekends.

public static class ExtensionMethods
{
    public static int GetNumberOfWorkingDays(this DateTime startDate, DateTime endDate)
    {
        int numberOfWorkingDays = 0;

        for (var nextDate = startDate; nextDate < endDate; nextDate = nextDate.AddDays(1))
        {
            if (nextDate.DayOfWeek != DayOfWeek.Saturday && nextDate.DayOfWeek != DayOfWeek.Sunday)
            {
                ++numberOfWorkingDays;
            }
        }

        return numberOfWorkingDays;
    }
}


and then call it from your code, e.g.

C#
var startDate = DateTime.Now;
var endDate = startDate.AddDays(10);
var numberDays = startDate.GetNumberOfWorkingDays(endDate);
 
Share this answer
 
One can always iterate... if the dates aren't too far apart. This code snippet assumes there are no holidays.
C#
using System;

namespace Codeproject.Answers
{
    public static class BusinessDaysCounter
    {
        public static long LeaveDays(DateTime from, DateTime to)
        {
            if (to < from)
            {
                return LeaveDays(to, from);
            }

            long days = 0;
            DateTime d = from;
            while (d <= to)
            {
                if (d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday)
                {
                    days++;
                }
                d = d.AddDays(1);
            }

            return days;
        }

    }
}
 
Share this answer
 
Here You Can Get The Total Number Of Days Between The Two Dates

C#
DateTime d1=DateTime.MinValue;
DateTime d2=DateTime.MaxValue;
TimeSpan span = d2 - d1;
Console.WriteLine
         ( "There're {0} days between {1} and {2}" , span.TotalDays, d1.ToString(), d2.ToString() );


For The Leaves You Have to Write A Separate Routine And Then Subtract It From Total Days.

Then You Will Get The Exact Number Of Days.
 
Share this answer
 
Comments
Aniket Yadav 7-Feb-12 8:20am    
Accept The Answer If It Has Helped You
Sergey Alexandrovich Kryukov 1-Mar-12 11:55am    
Right, a 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900