7

我需要检查从日期选择器中选择的日期是否不在周末。该函数需要不断检查新的开始日期是否为周末。如果周末发生,还需要在开始日期中添加天数。

代码应该是这样的:

int startday = Datepicker1.SelectedDate;
if (startdate = weekendday, startdate++)
{
 startdate++ //or if a sunday +2
}
else
{
 return startdate
}

感谢您的帮助。

4

5 回答 5

23
if (startdate.DayOfWeek == DayOfWeek.Saturday)
    startdate = startdate.AddDays(2);
else if (startdate.DayOfWeek == DayOfWeek.Sunday)
    startdate = startdate.AddDays(1);
于 2012-10-08T12:30:17.917 回答
4

使用该DayOfWeek属性,您可以明确检查周末。像这样的东西:

if ((startDate.DayOfWeek == DayOfWeek.Saturday) ||
    (startDate.DayOfWeek == DayOfWeek.Sunday))

当然,这对于一个条件来说有点长。将其抽象为辅助方法使其更简洁:

private bool IsWeekend(DateTime date)
{
    return (date.DayOfWeek == DayOfWeek.Saturday) ||
           (date.DayOfWeek == DayOfWeek.Sunday)
}

像这样使用:

if (IsWeekend(startDate))

或者,也许更简洁一点,您可以为以下内容编写扩展方法DateTime

public static bool IsWeekend(this DateTime date)
{
    return (date.DayOfWeek == DayOfWeek.Saturday) ||
           (date.DayOfWeek == DayOfWeek.Sunday)
}

你会像这样使用它:

if (startDate.IsWeekend())
于 2012-10-08T12:33:45.023 回答
0

看看DateTime.DayOfWeek记录在这里

while(startday.DayOfWeek == DayOfWeek.Saturday 
         || startday.DayOfWeek == DayOfWeek.Sunday)
{
   startday = startday.AddDays(1);
}
于 2012-10-08T12:29:27.817 回答
0

您可以简单地使用DateTime.DayOfWeek属性。来自 MSDN 的好例子:http: //msdn.microsoft.com/en-us/library/system.datetime.dayofweek.aspx

于 2012-10-08T12:29:34.717 回答
0

查看该DateTime.DayOfWeek属性 - 它会为您提供 DateTime 对象所在的星期几。

于 2012-10-08T12:31:02.600 回答