如何使用c#在asp.net中获取日历控件的当月周末列表
本文关键字:控件 列表 周末 日历 获取 何使用 asp net | 更新日期: 2023-09-27 18:00:32
我想得到当月周末的日期列表。有什么方法可以把所有周末的日期都存储在列表中吗
list<datetime> mylist=new list<datetime>();
我想把周末日期存储在当月的mylist中,与下个月相同我正在使用asp.net日历控件,我想把周末的日期保存在我的列表中。
对于当前月份,您可以进行
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);
}
}
你可以在下个月做一些类似的事情。
在每月的每一周重复此操作
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);
// 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;
}