How to handle an System.ArgumentOutOfRangeException when the last month is reached

Viewed 69

The following code section is used to output the date. I always need the following month. However, a System.ArgumentOutOfRangeException is thrown from this code:

DateTime startOfMonth = new DateTime(startTime.Year, startTime.Month+1, 1);

When startTime has reached the 12th month. As I understand it, the year is not increased by +1, which ultimately leads to this exception. I've tried to catch the exception but with no success. How can I handle this exception and take the year into account?

        public static List<string> GetMonthDays()
        {
            DateTime startTime = DateTime.Now;
            DateTime startOfMonth = new DateTime(startTime.Year, startTime.Month+1, 1);
            int daysInMonth = DateTime.DaysInMonth(startTime.Year, startTime.Month);
            List<string> currentMonth = new List<string>();
            //string[] currentMonth = new string[daysInMonth];
            for (int i = 0; i < daysInMonth; ++i)
            {
                DateTime currentDate = startOfMonth.AddDays(i);
                CultureInfo ci = new CultureInfo("de-DE");
                currentMonth.Add(currentDate.ToString("dddd - dd.MM.yy", ci));
            }
            return currentMonth;

        }
1 Answers

Change the following code ...

DateTime startOfMonth = new DateTime(startTime.Year, startTime.Month+1, 1);

To ...

DateTime startOfMonth = new DateTime(startTime.Year, startTime.Month, 1).AddMonths(1)
Related