跳过星期六和星期日,从ASP.NET当前日期开始获取日期?

时间:2013-10-10 14:17:32

标签: c# asp.net datetime

我使用以下代码跳过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日到来。

请告诉我我在哪里弄错了。

3 个答案:

答案 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;
}

Demo

答案 2 :(得分:0)

而不是从d变量中减去

如果是假日周六或周日

,请使用以下代码
date.Subtract(new TimeSpan(1, 0, 0, 0)); // where 1 is day count you need to subtract