Reputation: 6938
I am using the following code to skip the sat and sunday to get only the working days for a particular number of hours, actually what is my task:
I have a project and specific time to complete that, now i just want to show the date when the project will be complete.:
My code is:
DateTime date = DateTime.Now;
Int32 d = 1;
Int32 result = 260 / 8;
for (d = 0; d <= result; d++)
{
if (date.DayOfWeek.ToString() == "Saturday" || date.DayOfWeek.ToString() == "Sunday")
{
d = d - 1;
date = date.AddDays(1);
}
else
{
date = date.AddDays(1);
}
}
lbldate.Text = date.ToString();
Its working fine upto 30 days when days are 32 then date should come is :: 25th nov 2013 but it is coming 26th nov 2013.
please tell me where i am making mistake.
Upvotes: 0
Views: 1931
Reputation: 460360
Maybe there's something more elegant, but it works and doesn't need a loop:
public static DateTime GetDateIn(int numWorkingHours)
{
int numDays = numWorkingHours / 8;
DateTime date = DateTime.Now;
// normalize to monday
if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
date = date.AddDays(date.DayOfWeek == DayOfWeek.Sunday ? 1 : 2);
int weeks = numDays / 5;
int remainder = numDays % 5;
date = date.AddDays(weeks * 7 + remainder);
// normalize to monday
if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
date = date.AddDays(date.DayOfWeek == DayOfWeek.Sunday ? 1 : 2);
return date;
}
Upvotes: 1
Reputation:
A working solution would be:
DateTime endDate = DateTime.Now;
double remainingAmountOfWorkingDays = Math.Round(260d / 8d);
while (remainingAmountOfWorkingDays > 0)
{
endDate = endDate.AddDays(1);
if (endDate.DayOfWeek == DayOfWeek.Saturday || endDate.DayOfWeek == DayOfWeek.Sunday)
continue;
Console.WriteLine(remainingAmountOfWorkingDays +" "+endDate.ToString("dddd dd.MM.yyyy"));
remainingAmountOfWorkingDays--;
}
Upvotes: 1
Reputation: 104
Instead of subtracting from the d variable
use the following Code in case it's a Holiday Sat or Sun
date.Subtract(new TimeSpan(1, 0, 0, 0)); // where 1 is day count you need to subtract
Upvotes: 0