获取一个月中的天数


135

我有一个包含所有月份的comboBox。

我需要知道的是所选月份中的天数。

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

因此,如果用户选择一月,则需要将31保存到变量中。

Answers:


297

您要DateTime.DaysInMonth

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

显然,它随年份而变化,因为有时2月为28天,有时为29天。如果您想将其“固定”为一个值或另一个值,则始终可以选择一个特定的年份(是否跨越)。


30

从代码示例使用System.DateTime.DaysInMonth

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

3

为了找到一个月中的天数,DateTime类提供了一种方法“ DaysInMonth(int year,int month)”。 此方法返回指定月份中的总天数。

public int TotalNumberOfDaysInMonth(int year, int month)
    {
        return DateTime.DaysInMonth(year, month);
    }

要么

int days = DateTime.DaysInMonth(2018,05);

输出:-31


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

要么

 int days=System.Globalization.CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(int year,int month);

您必须通过年月,int否则月中的天数将在年月日归还


0

我让它根据选择的datetimepicker的月份和年份来计算月份中的天数,但是我更改了datetimepicker1中的代码以在带有此代码的文本框中返回结果

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

0
  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*/

-4
  • int days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);


如果您想查找今年和本月的日子,那最好

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.