我在我的WinForm上有2个组合框。获取所选月份和年份的第一天和最后一天?
combobox1 --> displaying months
combobox2 --> displaying years
如果我选择月和2017年它应该显示我是这样的:
1-wednesday
2-Thursday
.
.
.
到最后那个月只有
我在我的WinForm上有2个组合框。获取所选月份和年份的第一天和最后一天?
combobox1 --> displaying months
combobox2 --> displaying years
如果我选择月和2017年它应该显示我是这样的:
1-wednesday
2-Thursday
.
.
.
到最后那个月只有
,你可以做这样的:
//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
,其可用于甚至simplier解决方案:
//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"));
}
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
尝试你自己的东西首先。提示:使用DateTime.DaysInMonth –
首先尝试,并将您的代码放在哪里,如果您遇到困难,那么任何人都可以帮助您 –
如果您在说这个 DateTime date = new DateTime(); var lastDayOfMonth = DateTime.DaysInMonth(date.Year,date.Month); Console.WriteLine(lastDayOfMonth); 但它返回31 .. 我想知道关于31日的一天吗? –