tags:

views:

161

answers:

5

Normally I use the below code, but is there a better way?

lastOfMonth = new DateTime(Now.Year, Now.Month, 1).AddMonths(1).AddDays(-1)
+5  A: 

I use

DateTime now = DateTime.Today;
var lastDate = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month));
Mike Two
Returns a int, not a date.
Russell Steen
@Russell Steen, I misread the question at first and thought the OP just wanted the int. I've fixed it. Thanks.
Mike Two
+4  A: 
DateTime(year, month, DateTime.DaysInMonth(year, month)).
Kelsey
+2  A: 

You can use CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(Now.Year, Now.Month)

Timores
+2  A: 

I would probably use DaysInMonth as it makes the code a bit more readable and easier to understand (although, I really like your trick :-)). This requieres a similar ammount of typing (which is quite a lot), so I would probably define an extension method:

DateTime LastDayOfMonth(this DateTime) {
  var days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
  return new DateTime(DateTime.Now.Year, DateTime.Now.Month, days);
}

Now we can use DateTime.Now.LastDayOfMonth() which looks a lot better :-).

Tomas Petricek
An extension method would be a killer here.
Hamish Grubijan
A: 

Try Noda time library. http://code.google.com/p/noda-time/

ChiliYago