2013-02-23 134 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

相关问题