2017-05-29 186 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

相關問題