DateTime dt = new DateTime();
dt = DateTime.Now.AddMonths(1);
int x = DateTime.DaysInMonth(dt.Year, dt.Month);
MessageBox.Show(x.ToString()); // works ok - 31
>
You can also leverage Enumerable.Range
and LINQ (and the DaysOfWeek
enum)
DateTime dt = DateTime.Now.AddMonths(1);
Enumerable.Range(1, DateTime.DaysInMonth(dt.Year, dt.Month))
.Select(dayNumber => new DateTime(dt.Year, dt.Month, dayNumber))
.Select(dayName => dayName.DayOfWeek.ToString()).ToList()
.ForEach(day => MessageBox.Show(day));
The two .Select()
s can be merged but I kept them separated for readability.