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).
Asked
Active
Viewed 8,290 times
1
-
3Related http://stackoverflow.com/questions/1617049/calculate-the-number-of-business-days-between-two-dates – Soner Gönül Mar 12 '13 at 07:11
-
where is the list of holidays? – शेखर Mar 12 '13 at 07:28
-
Do you want to use a calendar to look up if a day is a holiday? For example in a Christian calendar _Good Friday_ may be a holiday even if it's not a Saturday or Sunday. – Jeppe Stig Nielsen Mar 12 '13 at 07:31
4 Answers
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);
-
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.
-
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; }
}
}