Thursday, January 24, 2013

How to count days between two dates except Saturday and Sunday in CSharp (C#)


To count days between two dates except Saturday and Sunday use the below C# code
public int CountDays(fromDate,toDate)  
{  
     int noOfDays = 0;  
     DateTime fDate = Convert.ToDateTime(fromDate);  
     DateTime tDate = Convert.ToDateTime(toDate);  
     while (DateTime.Compare(fDate, tDate) <= 0)  
     {  
          if (fDate.DayOfWeek != DayOfWeek.Saturday && fDate.DayOfWeek != DayOfWeek.Sunday)  
          {  
               noOfDays += 1;  
          }  

          fDate = fDate.AddDays(1);  
     }  
     
     return noOfDays;  
}  

2 comments:

  1. While this code works, it can be pretty slow since it is using a loop - especially if dealing with a large difference between dates or if running it against a large data set. The code below performs the same function but in a fraction of the time:

    public static int GetBusinessDays(DateTime startD, DateTime endD)
    {
    double calcBusinessDays =
    1 + ((endD - startD).TotalDays * 5 -
    (startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;

    if ((int)endD.DayOfWeek == 6) calcBusinessDays--;
    if ((int)startD.DayOfWeek == 0) calcBusinessDays--;

    return Convert.ToInt32(calcBusinessDays);
    }

    ReplyDelete