Select week days in asp.net Calendar programatical

2019-09-12 16:54发布

问题:

I'm trying to get all week days using below code.

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

But this is not working correctly. when i pass July month to getWeekDays(DateTime dt) method, this give all week days correctly. but if i pass August or Semptember, above code not return all week days of the given month.

Where is the error ?

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