tags:

views:

1107

answers:

3

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
Excellent! just done a unit test for this and works for both leap and non leap year!
J Angwenyi
+4  A: 
DateTime now = DateTime.Now;
DateTime lastDayOfLastMonth = now.Date.AddDays(-now.Day);
LukeH
Multiple DateTime.Now calls can be costly, as a new instance of the DateTime struct is created every time it's referenced.
opedog
@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
That is true, sir. :)
opedog
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
@Eric: Good point, kicking myself for not spotting that one! Edited accordingly - now it's faster *and* correct!
LukeH
+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
-1 because the other solutions are so much more ingenious
tomfanning
@tomfanning... pardon? How is it MORE ingenious to NOT use the function that is meant to do exactly what you want?
So the quality of an answer can only be evaluated when compared to others?
Richard C. McGuire
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