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
  1. public int CountDays(fromDate,toDate)
  2. {
  3. int noOfDays = 0;
  4. DateTime fDate = Convert.ToDateTime(fromDate);
  5. DateTime tDate = Convert.ToDateTime(toDate);
  6. while (DateTime.Compare(fDate, tDate) <= 0)
  7. {
  8. if (fDate.DayOfWeek != DayOfWeek.Saturday && fDate.DayOfWeek != DayOfWeek.Sunday)
  9. {
  10. noOfDays += 1;
  11. }
  12.  
  13. fDate = fDate.AddDays(1);
  14. }
  15. return noOfDays;
  16. }

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