如何列出从过去的日期到当月的月份和年份

时间:2010-08-18 08:14:46

标签: c# datetime

我希望从过去的某个时间点到当月有几个月和几年的下拉列表。 这是我的代码:

for (int year = 2009; year <= DateTime.Now.Year; year++)
{
   for (int month = 1; month <= 12; month++)
   {
      DateTime date = new DateTime(year, month, 1);
      this.MonthsCombo.Items.Add(
          new RadComboBoxItem(date.ToString("Y"), 
                              String.Format("{0};{1}", year, month))); // this is for reading selected value
   }
}

如何更改该代码,以便上个月是当月?

1 个答案:

答案 0 :(得分:2)

如果ity小于今天,则仅添加值。

if (date <= DateTime.Today)
{
    this.MonthsCombo.Items.Add( 
          new RadComboBoxItem(month.ToString("Y"),  
                              String.Format("{0};{1}", year, m))); // this is for reading selected value 
}

或者,我会做一个while循环,比如

DateTime startDate = new DateTime(2009, 01, 01);
while (startDate <= DateTime.Today)
{

    startDate = startDate.AddMonths(1);
}