Calculating first and last day of a month using and C#

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

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

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


5 thoughts on “Calculating first and last day of a month using and C#

  1. Anonymous

    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. ๐Ÿ™‚

  2. Anoop ms

    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!


Leave a Reply

Your email address will not be published. Required fields are marked *