让我们考虑一下我有两个日期字段。
DateTime dt1 = "01/04/2012"
DateTime dt2 = "31/08/2012"
这里我的日期是“DD/MM/YYYY”格式。这里 dt1 是开始日期,dt2 是结束日期。从两个日期字段中,我可以知道它位于 04,05,06,07,08 月份。
所以我想在我的下拉列表中显示月份和年份的组合。
04/2012
05/2012
06/2012
07/2012
08/2012
我怎样才能做到这一点?
让我们考虑一下我有两个日期字段。
DateTime dt1 = "01/04/2012"
DateTime dt2 = "31/08/2012"
这里我的日期是“DD/MM/YYYY”格式。这里 dt1 是开始日期,dt2 是结束日期。从两个日期字段中,我可以知道它位于 04,05,06,07,08 月份。
所以我想在我的下拉列表中显示月份和年份的组合。
04/2012
05/2012
06/2012
07/2012
08/2012
我怎样才能做到这一点?
如果 Asp.net:
DateTime dt1 = new DateTime();
dt1 = DateTime.ParseExact("01/04/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture);
DateTime dt2 = new DateTime();
dt2 = DateTime.ParseExact("31/08/2012", "dd/M/yyyy", CultureInfo.InvariantCulture);
while (dt2 > dt1)
{
dt1 = dt1.AddMonths(1);
this.dateDropDownList.Items.Add(dt1.ToString("MM / yyyy", CultureInfo.InvariantCulture));
}
如果窗口形式:
DateTime dt1 = new DateTime();
dt1 = DateTime.ParseExact("01/04/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture);
DateTime dt2 = new DateTime();
dt2 = DateTime.ParseExact("31/08/2012", "dd/M/yyyy", CultureInfo.InvariantCulture);
while (dt2 > dt1)
{
dt1 = dt1.AddMonths(1);
this.dateComboBox.Items.Add(dt1.ToString("MM / yyyy", CultureInfo.InvariantCulture));
}
DateTime dt1 = new DateTime(2012,04,01);
DateTime dt2 = new DateTime(2012,08,30);
int firstMonth = dt1.Month;
int lastMonth =dt2.Month;
//Then you can compare the two numbers as you like
Something like below will give you a list of string, that you can use to bind to the drop down.
DateTime dt1 = DateTime.ParseExact("01/04/2012", "d/M/yyyy", CultureInfo.InvariantCulture);
DateTime dt2 = DateTime.ParseExact("31/08/2012", "d/M/yyyy", CultureInfo.InvariantCulture);
List<string> list = new List<string>();
while (dt2 > dt1)
{
list.Add(dt1.Month + "/" + dt1.Year);
dt1 = dt1.AddMonths(1);
}
If you output it using foreach you will get:
foreach (string str in list)
{
Console.WriteLine(str);
}
4/2012
5/2012
6/2012
7/2012
8/2012
Later if its ASP.Net (because you used dropdownlist), you can do
DropDownList1.DataSource = list;
DropDownList1.DataBind();
你可以这样做:
int firstMonth = Int32.Parse(dt1.Month);
int secondMonth = Int32.Parse(dt2.Month);
int year = Int32.Parse(dt1.Year);
// You could do some checking if the year is different or something.
for(int month = firstMonth; month <= secondMonth; month++)
// Add the date to the drop down list by using (month + year).ToString()
希望这可以帮助!