以编程方式在asp.net日历中选择工作日

时间:2013-07-01 04:20:57

标签: c# asp.net datetime calendar

我正在尝试使用以下代码获取所有工作日。

    private List<DateTime> getWeekDays(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 day of the month;
        if (dt.DayOfWeek != DayOfWeek.Monday)
            while (dt.DayOfWeek != DayOfWeek.Friday)
                dt = dt.AddDays(1);

        //Adds the week day and stops when next month is reached.
        while (dt.Month == month)
        {
            result.Add(dt);
            dt = dt.AddDays(dt.DayOfWeek == DayOfWeek.Friday ? 3 : 1);
        }
        return result;
    }

但这不能正常工作。当我将July月传递给getWeekDays(DateTime dt)方法时,这会正确地给出所有工作日。但如果我通过AugustSemptember,则上述代码不会返回给定月份的所有工作日。

错误在哪里?

1 个答案:

答案 0 :(得分:1)

        private List<DateTime> getWeekDays(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

            //If dt is a weekend add days to move it to Monday (your while loop below will handle the rest)
            if(dt.DayOfWeek == DayOfWeek.Saturday)
            {
                dt = dt.AddDays(2);
            }
            else if (dt.DayOfWeek == DayOfWeek.Sunday)
            {
                dt = dt.AddDays(1);
            }

            //Adds the week day and stops when next month is reached.
            while (dt.Month == month)
            {
                result.Add(dt);
                dt = dt.AddDays(dt.DayOfWeek == DayOfWeek.Friday ? 3 : 1);
            }

            return result;
        }