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.
I made it calculate days in month from datetimepicker selected month and year , and I but the code in datetimepicker1 textchanged to return the result in a textbox with this code
private void DateTimePicker1_ValueChanged(object sender, EventArgs e)
{
int s = System.DateTime.DaysInMonth(DateTimePicker1.Value.Date.Year, DateTimePicker1.Value.Date.Month);
TextBox1.Text = s.ToString();
}
int days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
if you want to find days in this year and present month then this is best
To find the number of days in a month, DateTime class provides a method "DaysInMonth(int year, int month)". This method returns the total number of days in a specified month.
public int TotalNumberOfDaysInMonth(int year, int month)
{
return DateTime.DaysInMonth(year, month);
}
OR
int days = DateTime.DaysInMonth(2018,05);
Output :- 31
Use System.DateTime.DaysInMonth, from code sample:
const int July = 7;
const int Feb = 2;
// daysInJuly gets 31.
int daysInJuly = System.DateTime.DaysInMonth(2001, July);
// daysInFeb gets 28 because the year 1998 was not a leap year.
int daysInFeb = System.DateTime.DaysInMonth(1998, Feb);
// daysInFebLeap gets 29 because the year 1996 was a leap year.
int daysInFebLeap = System.DateTime.DaysInMonth(1996, Feb);
int days = DateTime.DaysInMonth(int year,int month);
or
int days=System.Globalization.CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(int year,int month);
you have to pass year and month as int
then days in month will be return on currespoting year and month
int month = Convert.ToInt32(ddlMonth.SelectedValue);/*Store month Value From page*/
int year = Convert.ToInt32(txtYear.Value);/*Store Year Value From page*/
int days = System.DateTime.DaysInMonth(year, month); /*this will store no. of days for month, year that we store*/
Source: Stackoverflow.com