A quick expression anyone please?
+21
A:
DateTime now = DateTime.Now;
DateTime lastDayLastMonth = new DateTime(now.Year, now.Month, 1);
lastDayLastMonth = lastDayLastMonth.AddDays(-1);
Seb Nilsson
2009-07-16 14:51:10
Excellent! just done a unit test for this and works for both leap and non leap year!
J Angwenyi
2009-07-16 15:14:29
+4
A:
DateTime now = DateTime.Now;
DateTime lastDayOfLastMonth = now.Date.AddDays(-now.Day);
LukeH
2009-07-16 14:51:19
Multiple DateTime.Now calls can be costly, as a new instance of the DateTime struct is created every time it's referenced.
opedog
2009-07-16 14:53:08
@opedog: Costly is a relative term. This *slow* version can manage about 1.7M iterations/second on my machine, compared to about 2.7M iterations/second if I call `DateTime.Now` once and re-use the instance. Certainly a decent improvement, but I doubt if it would be noticed in most real-world situations.
LukeH
2009-07-16 15:06:41
The problem isn't that the code is *costly*. The problem is that the code is *wrong* because it has a *race condition*. What if the code runs such that the first call to Now happens at 23:59:59.9999 on Nov 30th, and the second call to Now happens at 12:00:00.0001 on December 1st? Race conditions aren't just a problem in threading situations; they're a problem in any situation in which exact details of timing matter.
Eric Lippert
2009-07-16 16:19:14
@Eric: Good point, kicking myself for not spotting that one! Edited accordingly - now it's faster *and* correct!
LukeH
2009-07-16 16:30:29
+1
A:
Try the DateTime.DaysInMonth(int year, int month) method
Here's an example:
DateTime oneMonthAgo = DateTime.Now.AddMonths(-1);
int days = DateTime.DaysInMonth(oneMonthAgo.Year, oneMonthAgo.Month);
Richard C. McGuire
2009-07-16 14:54:24
@tomfanning... pardon? How is it MORE ingenious to NOT use the function that is meant to do exactly what you want?
2009-07-16 15:11:02
So the quality of an answer can only be evaluated when compared to others?
Richard C. McGuire
2009-07-16 15:11:37
I prefer the elegance of the "work out first day of this month, take a day off" approach where you don't ever have to take account of the exceptional case (January).
tomfanning
2009-07-16 21:13:05