我想获得当月周末的日期列表。 有什么办法可以将所有周末日期存储在我的列表中
list<datetime> mylist=new list<datetime>();
我想将周末日期存储在当月的mylist中,并与下个月相同 我使用asp.net日历控件,我想在我的列表中保存周末日期。
答案 0 :(得分:4)
本月,您可以
var startDate = DateTime.Now;
var first = new DateTime(startDate.Year, startDate.Month, 1);
List<DateTime> weekends = new List<DateTime>();
for (int i = 0; i <= DateTime.DaysInMonth(startDate.Year, startDate.Month); i++)
{
var nextDay = first.AddDays(i);
if (nextDay.DayOfWeek == DayOfWeek.Saturday || nextDay.DayOfWeek == DayOfWeek.Sunday)
{
weekends.Add(nextDay);
}
}
下个月你可以做一些非常相似的事情。
答案 1 :(得分:0)
每月的每个星期都重复这个
DateTime date = DateTime.Now;
DateTime saturday;
DateTime sunday;
if (date.DayOfWeek == DayOfWeek.Monday)
{
saturday = date.AddDays(5);
sunday = date.AddDays(6);
}else if (date.DayOfWeek == DayOfWeek.Tuesday)
{
saturday = date.AddDays(4);
sunday = date.AddDays(5);
}
else if (date.DayOfWeek == DayOfWeek.Wednesday)
{
saturday = date.AddDays(3);
sunday = date.AddDays(4);
}
else if (date.DayOfWeek == DayOfWeek.Thursday)
{
saturday = date.AddDays(2);
sunday = date.AddDays(3);
}
else if (date.DayOfWeek == DayOfWeek.Friday)
{
saturday = date.AddDays(1);
sunday = date.AddDays(2);
}
else if (date.DayOfWeek == DayOfWeek.Saturday)
{
saturday = date.AddDays(0);
sunday = date.AddDays(1);
}
else if (date.DayOfWeek == DayOfWeek.Sunday)
{
saturday = date.AddDays(-1);
sunday = date.AddDays(0);
}
请注意:
下周:
date.AddDays(7);
前一周:
date.AddDays(-7);
答案 2 :(得分:0)
// Get weekend days of visible moth
public List<DateTime> getWeekEndDays(DateTime dt)
{
List<DateTime> result = new List<DateTime>();
int month = dt.Month;
dt = dt.AddDays(-dt.Day + 1);//Sets dt to first day of month
//Sets dt to the first week-end day of the month;
if (dt.DayOfWeek != DayOfWeek.Sunday)
while (dt.DayOfWeek != DayOfWeek.Saturday)
dt = dt.AddDays(1);
//Adds the week-end day and stops when next month is reached.
while (dt.Month == month)
{
result.Add(dt);
dt = dt.AddDays(dt.DayOfWeek == DayOfWeek.Saturday ? 1 : 6);
}
return result;
}