0

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

    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)方法时,这会正确给出所有工作日。但如果我通过Augustor Semptember,上面的代码不会返回给定月份的所有工作日。

错误在哪里?

4

1 回答 1

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;
        }
于 2013-07-01T04:49:57.710 回答