我需要检查从日期选择器中选择的日期是否不在周末。该函数需要不断检查新的开始日期是否为周末。如果周末发生,还需要在开始日期中添加天数。
代码应该是这样的:
int startday = Datepicker1.SelectedDate;
if (startdate = weekendday, startdate++)
{
startdate++ //or if a sunday +2
}
else
{
return startdate
}
感谢您的帮助。
我需要检查从日期选择器中选择的日期是否不在周末。该函数需要不断检查新的开始日期是否为周末。如果周末发生,还需要在开始日期中添加天数。
代码应该是这样的:
int startday = Datepicker1.SelectedDate;
if (startdate = weekendday, startdate++)
{
startdate++ //or if a sunday +2
}
else
{
return startdate
}
感谢您的帮助。
if (startdate.DayOfWeek == DayOfWeek.Saturday)
startdate = startdate.AddDays(2);
else if (startdate.DayOfWeek == DayOfWeek.Sunday)
startdate = startdate.AddDays(1);
使用该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())
看看DateTime.DayOfWeek
记录在这里。
while(startday.DayOfWeek == DayOfWeek.Saturday
|| startday.DayOfWeek == DayOfWeek.Sunday)
{
startday = startday.AddDays(1);
}
您可以简单地使用DateTime.DayOfWeek
属性。来自 MSDN 的好例子:http: //msdn.microsoft.com/en-us/library/system.datetime.dayofweek.aspx
查看该DateTime.DayOfWeek
属性 - 它会为您提供 DateTime 对象所在的星期几。