In this post, I'm going to show you how calculate the first day and last day of a month for one of the project. The method that I'm using is very simple.

Here is the code:

DateTime today = DateTime.Now; //current date

DateTime firstDay = today.AddDays(-(today.Day - 1)); //first day

today = today.AddMonths(1);
DateTime lastDay = today.AddDays(-(today.Day)); //last day

The Explanation

The Calculation of First Day

DateTime firstDay = today.AddDays(-(today.Day - 1));

Here I'm using the AddDays method which can add given number of days to the current date. Using today.Day I'm extracting the current date day as integer value, which is 21 in my example. The tricky part here is that I'm adding with the AddDays method total of 21-1 = 20 and using the minus sign, it's getting 20 days back (instead of 20 days forward).

The Calculation of the Last Day

today = today.AddMonths(1);
DateTime lastDay = today.AddDays(-(today.Day)); //last day

With today = today.AddMonths(1) I'm adding one month plus to the current date.
Before adding, for example the today value was {21-07-2015 17:27:50} - after adding +1 month, the today value is {21-08-2015 17:27:50}.
Then, with the last line, the trick is very similar to the firstDayDate calculation, we only go in minus to the number of days got from the today.Day integer value. We do not add today.Day-1 here because if you do, you will get the first day of the next month (so you know one more thing now, how to get the first day of the next month).
The lastDay value will be 31-07-2015 17:27:50

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.