2013-02-23 89 views
2

我有一個存儲在會話變量中的日期,然後將其轉換爲日期。現在我想獲得通過日期的月份的第一個和最後一個日期。要做到這一點傳遞日期並獲得該月的第一個和最後一個日期?

DateTime tempDate = System.Convert.ToDateTime(Session["Diary_Date"]); 
DateTime startOfMonth = //what goes here? 
DateTime endOfMonth = //?? 

回答

7

方式一:

DateTime startOfMonth = new DateTime(tempDate.Year, tempDate.Month, 1); 
DateTime endOfMonth = startOfMonth.AddMonths(1).AddDays(-1); 
+0

這就是偉大的感謝 – John 2013-02-23 18:29:15

5

另一種方式是

DateTime startOfMonth = new DateTime(tempDate.Year, tempDate.Month, 1); 
DateTime endOfMonth = new DateTime(tempDate.Year, tempDate.Month, DateTime.DaysInMonth(tempDate.Year, tempDate.Month)); 
+1

+1奇怪,爲什麼我總是用'CultureInfo.CurrentCulture.Calendar.GetDaysInMonth 「而不是? – 2013-02-23 18:28:49

+0

好的,謝謝你 – John 2013-02-23 19:03:47

+1

Man!這是我正在尋找的。謝謝。 – Avy 2015-05-01 11:19:34

相關問題