Some days ago I needed to calculate the first day and last day of a month for one of the project I am working on. I got some ideas while googling, and I wrote a code.The method I am using is 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

Explanation:

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

So, 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).

-(today.Day - 1) is actually -(21-1) = 01-07-2010 17:27:50

Next, the calculation of the LastDay

-(today.Day - 1) is actually -(21-1) = 01-07-2010 17:27:50

Next, the calculation of the LastDay

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, the today value was {21-07-2010 17:27:50} - after adding +1 month, the today value is {21-08-2010 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 we do, we 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-2010 17:27:50

Cheers
Before adding, the today value was {21-07-2010 17:27:50} - after adding +1 month, the today value is {21-08-2010 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 we do, we 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-2010 17:27:50

## 5 comments:

Nice code. Thanks

Thanks...

Thanks for this! But how would I remove the date or make it the default 12:00:00 AM? Thanks for any response of yours. :)

If you take the "Date" Property of any DateTime object you will get the default "12:00:00 am" as the time, or you can use ToShortDate() or ToLongDate() extensions to return only date, without time. Hope it helps you!

Thanks for this post..

asp.net training in jaipur

## Post a Comment