我的WinForm上有2个ComboBox。
combobox1 --> displaying months
combobox2 --> displaying years
如果我选择2017年1月和2017年它应该显示如下:
1-wednesday
2-Thursday
.
.
.
直到那个月的最后一天
答案 0 :(得分:1)
//clear items
comboBox1.Items.Clear();
int month = 5;
int year = 2017;
//new datetime with specified year and month
DateTime startDate = new DateTime(year, month, 1);
//from first day of this month until first day of next month
for (int i = 0; i < (startDate.AddMonths(1) - startDate).Days; i++)
{
//add one day to start date and add that in "number - short day name" in combobox
this.comboBox1.Items.Add(startDate.AddDays(i).ToString("dd - ddd"));
}
编辑:我忘记了DateTime.DaysInMonth
,它可以用于更简单的解决方案:
//clear items
comboBox1.Items.Clear();
int month = 5;
int year = 2017;
//calculate how many days are in specified month
int daysInMonth = DateTime.DaysInMonth(year, month);
//loop through all days in month
for (int i = 1; i <= daysInMonth; i++)
{
//add one day to start date and add that in "number - short day name" in combobox
this.comboBox1.Items.Add(new DateTime(year, month, i).ToString("dd - ddd"));
}
答案 1 :(得分:0)
DateTime
结构只存储一个值,而不存储值范围。 MinValue
和MaxValue
是静态字段,其中包含DateTime
结构实例的可能值范围。这些字段是静态的,与DateTime
的特定实例无关。它们与DateTime
类型本身有关。
DateTime date = ...
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
参考here