选择工作日在asp.net日历编程(Select week days in asp.net Cale

2019-10-29 06:00发布

我试图让所有的工作日使用下面的代码。

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

但是,这不能正常工作。 当我通过JulygetWeekDays(DateTime dt)的方法,这个正确尽数工作日。 但如果我通过AugustSemptember ,上面的代码不会返回给定月份的所有工作日。

哪里的错误?

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


文章来源: Select week days in asp.net Calendar programatically