【问题标题】:Getting number of days in a month获取一个月的天数
【发布时间】:2011-01-28 19:58:27
【问题描述】:

我有一个包含所有月份的组合框。

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

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

所以如果用户选择一月,我需要将 31 保存到变量中。

【问题讨论】:

    标签: c# datetime


    【解决方案1】:

    你想要DateTime.DaysInMonth:

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

    显然它因年而异,因为有时 2 月有 28 天,有时有 29 天。如果您想将其“修复”为一个值或其他值,您总是可以选择一个特定的年份(无论是否闰年)。

    【讨论】:

      【解决方案2】:

      使用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

        【讨论】:

          【解决方案4】:
            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*/
          

          【讨论】:

            【解决方案5】:
             int days = DateTime.DaysInMonth(int year,int month);
            

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

            您必须将年份和月份传递为int,然后月份中的天数将返回当前年份和月份

            【讨论】:

              【解决方案6】:

              我让它根据 datetimepicker 选择的月份和年份计算月份中的天数,但我在 datetimepicker1 中的代码 textchanged 以在文本框中返回结果 使用此代码

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

              【讨论】:

                【解决方案7】:
                • int days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);


                如果你想找到今年和当前月份的日子,那么这是最好的

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2011-10-19
                  • 1970-01-01
                  • 2014-08-15
                  • 1970-01-01
                  • 2021-07-30
                  • 2013-02-14
                  相关资源
                  最近更新 更多