开发者

how to get current month Weekends list of calender control in asp.net using c#

i want to get the list of dates of weekend of current month. is there is any way i can store all weekend dates in my list

list<datetime> mylist=new list<datetime>开发者_StackOverflow中文版();

i want to store the weekend dates in mylist of current month and same with next months i m using asp.net calender control and i want to save the date of weekend in my list.


For current month, you can do

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);
    }
}

You can do something very similar for next month.


repeat this for every week of month

 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);
        }

note:

next week:

date.AddDays(7);

previous week:

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜