Search code examples
c#datetime

Getting number of days in a month


I have a comboBox with all of the months in it.

What I need to know is the number of days in the chosen month.

var month = cmbMonth.SelectedIndex + 1;
DateTime date = Convert.ToDateTime(month);

So if a user selects January, I need to save 31 to a variable.


Solution

  • You want DateTime.DaysInMonth:

    int days = DateTime.DaysInMonth(year, month);
    

    Obviously it varies by year, as sometimes February has 28 days and sometimes 29. You could always pick a particular year (leap or not) if you want to "fix" it to one value or other.