我试图获取所选月份的所有工作日以及周一或周二等日期等等?这怎么可能?是否有一个我不知道的内置函数?
这是在C#2.0,使用VS 2005的asp.net
答案 0 :(得分:4)
我不保证闰年,夏令时跳跃,特殊日子,Shanghai 1927等。
public List<DateTime> getWeekdatesandDates(int Month, int Year)
{
List<DateTime> weekdays = new List<DateTime>();
DateTime firstOfMonth = new DateTime(Year, Month, 1);
DateTime currentDay = firstOfMonth;
while (firstOfMonth.Month == currentDay.Month)
{
DayOfWeek dayOfWeek = currentDay.DayOfWeek;
if (dayOfWeek != DayOfWeek.Saturday && dayOfWeek != DayOfWeek.Sunday)
weekdays.Add(currentDay);
currentDay = currentDay.AddDays(1);
}
return weekdays;
}
生成的DateTime
对象具有DayOfWeek
属性,您可以检查它是否是星期一到星期五。
答案 1 :(得分:1)
这应该有效
private List<DateTime> getWeekDayDates(int month, int year)
{
List<DateTime> weekdays = new List<DateTime>();
DateTime basedt = new DateTime(year, month, 1);
while ((basedt.Month == month) && (basedt.Year == year))
{
if (basedt.DayOfWeek == (DayOfWeek.Monday | DayOfWeek.Tuesday | DayOfWeek.Wednesday | DayOfWeek.Thursday | DayOfWeek.Friday))
{
weekdays.Add(new DateTime(basedt.Year, basedt.Month, basedt.Day));
}
basedt = basedt.AddDays(1);
}
return weekdays;
}
然后,您可以从每个DateTime获取所需的任何信息。