确定begindate是否是周末

时间:2012-10-08 12:27:34

标签: c#

我需要检查来自日期选择器的所选日期是否不在周末。该函数需要继续检查新的startdate是否是一个周末。如果周末发生,它还需要在startdate中添加天数。

代码应该是这样的:

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

感谢您的帮助。

5 个答案:

答案 0 :(得分:23)

if (startdate.DayOfWeek == DayOfWeek.Saturday)
    startdate = startdate.AddDays(2);
else if (startdate.DayOfWeek == DayOfWeek.Sunday)
    startdate = startdate.AddDays(1);

答案 1 :(得分: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())

答案 2 :(得分:0)

查看DateTime.DayOfWeek记录的here

while(startday.DayOfWeek == DayOfWeek.Saturday 
         || startday.DayOfWeek == DayOfWeek.Sunday)
{
   startday = startday.AddDays(1);
}

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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