2017-05-29 185 views
-3

我在我的WinForm上有2个组合框。获取所选月份和年份的第一天和最后一天?

combobox1 --> displaying months 
combobox2 --> displaying years 

如果我选择月和2017年它应该显示我是这样的:

1-wednesday 
2-Thursday 
. 
. 
. 

到最后那个月只有

+7

尝试你自己的东西首先。提示:使用DateTime.DaysInMonth –

+0

首先尝试,并将您的代码放在哪里,如果您遇到困难,那么任何人都可以帮助您 –

+0

如果您在说这个 DateTime date = new DateTime(); var lastDayOfMonth = DateTime.DaysInMonth(date.Year,date.Month); Console.WriteLine(lastDayOfMonth); 但它返回31 .. 我想知道关于31日的一天吗? –

回答

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,其可用于甚至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")); 
} 
+0

一个词 - 完美(Y) –

+0

@Ivar它是相同的,因为'for'的条件部分不是每次迭代计算,而是只计算一次。 – Nino

+1

@Ivar ooops,你是对的!感谢您的注意。我编辑了我的答案。 – Nino

0

DateTime结构存储一个值,而不是值的范围。 MinValueMaxValue是静态字段,其中保存DateTime结构实例的可能值范围。这些字段是静态的,并且与DateTime的特定实例无关。它们与DateTime类型本身有关。

DateTime date = ... 
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1); 
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1); 

参考here

相关问题