让我们考虑一下我有两个日期字段。
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
我怎样才能做到这一点?
答案 0 :(得分:0)
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
答案 1 :(得分:0)
下面的内容将为您提供一个字符串列表,您可以使用它来绑定到下拉列表。
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);
}
如果使用foreach输出它,您将获得:
foreach (string str in list)
{
Console.WriteLine(str);
}
4/2012
5/2012
6/2012
7/2012
8/2012
稍后如果它的ASP.Net(因为你使用了dropdownlist),你可以做
DropDownList1.DataSource = list;
DropDownList1.DataBind();
答案 2 :(得分:0)
你可以这样做:
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()
希望这有帮助!
答案 3 :(得分:0)
如果是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));
}