简体   繁体   中英

Code to calculate no.of days between two dates

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).

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);
 var dateDiff = FirstDate - SecondDate; 
 double totalDays = dateDiff.TotalDays;

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.

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; }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM