Reputation: 9
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).
Upvotes: 1
Views: 8348
Reputation: 2000
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; }
}
}
Upvotes: 1
Reputation: 6651
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.
Upvotes: 1
Reputation: 223187
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);
Upvotes: 3
Reputation: 2983
var dateDiff = FirstDate - SecondDate;
double totalDays = dateDiff.TotalDays;
Upvotes: 2