Click here to Skip to main content
16,017,238 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i have the codes below, but when i run the program, the count would always stuck at zero...
eg. if i entered 3/3/2014 and daysInWeek as 4, it should return 2 for the count but it give me 0 instead. Any help would be appreciated.

C#
string datetime = txtEffectiveDate.Text;
DateTime startDate = Convert.ToDateTime(datetime); // date entered by users
int daysInWeek = Convert.ToInt32(txtDaysInWeek.Text); //no. of days entered by users
DateTime previousDate = startDate.AddDays(-daysInWeek); // date after subtracted from ori dates above

TimeSpan preDiff = previousDate - startDate;
int preDays = preDiff.Days;
 
for (var j = 0; j <= preDays; j++)
{
   var pretestDate = startDate.AddDays(-j);
   switch (pretestDate.DayOfWeek)
   {
      case DayOfWeek.Saturday:
      count++;
      break;
      case DayOfWeek.Sunday:
      count++;
      break;
 
   }
}
 
MessageBox.Show("You have " + count + " days off");
Posted

Well...you don't do anything with count, unless it's a Saturday or Sunday, so you probably need to look at that, but the main problem is pretty obvious, if you quickly run trough with the debugger.
Put a breakpoint on this line:
C#
for (var j = 0; j <= preDays; j++)
And look at the value of preDays.
What is it?
Answer, -4.
And is 0 <= -4 ?
No. So your loop is never executed - as you would have seen if you had tried using the debugger to step through the code. Probably, you wanted to reverse this:
C#
TimeSpan preDiff = previousDate - startDate;
To this:
C#
TimeSpan preDiff = startDate - previousDate;
But...since this just works out the number you first thought of - daysInWeek - why do it at all?
 
Share this answer
 
Stepping through that code with your debugger would have shown you that your TimeSpan value was negative. Change it to:
C#
TimeSpan preDiff = startDate - previousDate;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900