我使用以下代码跳过sat和sunday只获得特定小时数的工作日,实际上我的任务是什么:
我有一个项目和具体时间来完成,现在我只想显示项目完成的日期。:
我的代码是:
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();
它的工作时间长达30天,当天数为32,那么日期应该是2013年11月25日 但它将于2013年11月26日到来。
请告诉我我在哪里弄错了。答案 0 :(得分:1)
一个有效的解决方案是:
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--;
}
答案 1 :(得分:1)
也许有更优雅的东西,但它有效并且不需要循环:
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;
}
答案 2 :(得分:0)
而不是从d变量中减去
如果是假日周六或周日
,请使用以下代码date.Subtract(new TimeSpan(1, 0, 0, 0)); // where 1 is day count you need to subtract