Jonathan Allen
Jonathan Allen

Reputation: 70287

Last day of the month in .NET

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

lastOfMonth = new DateTime(Now.Year, Now.Month, 1).AddMonths(1).AddDays(-1)

Upvotes: 46

Views: 18458

Answers (5)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241450

Here is how you can get the number of days in the month using Noda Time:

int days = CalendarSystem.Iso.GetDaysInMonth(year, month);

Pretty simple, eh? Well that assumes you know the year and month you are asking about. If you want it for the current month, and in the system's time zone, then you have to specify that explicitly, like this:

DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault();
LocalDate localDate = SystemClock.Instance.Now.InZone(tz).Date;
int days = localDate.Calendar.GetDaysInMonth(localDate.Year, localDate.Month);

Noda Time intentionally makes you think about these things, instead of just making the assumptions that DateTime.Now or DateTime.Today do.

Upvotes: 2

Tomas Petricek
Tomas Petricek

Reputation: 243041

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 :-).

Upvotes: 14

Timores
Timores

Reputation: 14589

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

Upvotes: 6

Kelsey
Kelsey

Reputation: 47726

DateTime(year, month, DateTime.DaysInMonth(year, month)).

Upvotes: 12

Mike Two
Mike Two

Reputation: 46173

I use

DateTime now = DateTime.Today;
var lastDate = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month));

Upvotes: 82

Related Questions