1

C# Code to calculate no.of days between two dates...I have start date in one textbox and end date in another textbox and i need to get no. of days between the two dates and to be displayed in third textbox and it should exclude holidays and weekends(saturday and sunday).

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
user2159740
  • 9
  • 1
  • 4

4 Answers4

3

You can parse the textbox dates to date time object and then try something on the following lines.

DateTime startDate = new DateTime(2013, 03, 01);
DateTime endDate = DateTime.Today; // 12 March 2013
int totalDays = 0;
while (startDate <= endDate)
{
    if (startDate.DayOfWeek == DayOfWeek.Saturday
        || startDate.DayOfWeek == DayOfWeek.Sunday)
    {
        startDate = startDate.AddDays(1);
        continue;
    }
    startDate = startDate.AddDays(1);
    totalDays++;
}

Console.WriteLine("Total days excluding weekends: {0}", totalDays);
albertjan
  • 7,739
  • 6
  • 44
  • 74
Habib
  • 219,104
  • 29
  • 407
  • 436
  • If you want to count all days including weekends I wouldn't want to use this. This should only be used when you don't want to include the weekends. – albertjan Mar 12 '13 at 07:25
  • @albertjan, yes otherwise `TimeSpan.TotalDays` property is enough for calculating difference between two dates. – Habib Mar 12 '13 at 07:27
2
 var dateDiff = FirstDate - SecondDate; 
 double totalDays = dateDiff.TotalDays;
Radislav
  • 2,892
  • 7
  • 38
  • 61
1

if you have two dates in textboxes viz textBox1 and textBox2

DateTime date1= new DateTime();
DateTime date2 = new DateTime();
double days;

bool isDate1Valid =DateTime.TryParse(textBox1.Text, out date1);
bool isDate2Valid =DateTime.TryParse(textBox2.Text, out date2);

if(isDate1Valid && isDate2Valid)
days = (date1-date2).TotalDays;

Edit

If you need to do it without looping, Here is how to do it..

If date difference is too large, looping may consume some amount of extra time.

Community
  • 1
  • 1
Marshal
  • 6,551
  • 13
  • 55
  • 91
  • 1
    `it should exclude holidays and weekends(saturday and sunday).` that is n the question. TotalDays will not exclude that – Habib Mar 12 '13 at 07:24
1

Try this..

    DateTime startdate = DateTime.Parse("somedate");
    DateTime enddate = DateTime.Parse("somedate");
    int daycount = 0;
    while (startdate < enddate)
    {
        startdate = startdate.AddDays(1); // Fixed
        int DayNumInWeek = (int)startdate.DayOfWeek;
        if (DayNumInWeek != 0)
        {
            if (DayNumInWeek != 6)
            { daycount += 1; }
        }
    }
Community
  • 1
  • 1
coder
  • 1,980
  • 3
  • 21
  • 32