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

1 |
DateTime today = DateTime.Now; //current date<br /><br />DateTime firstDay = today.AddDays(-(today.Day - 1)); //first day<br /><br />today = today.AddMonths(1);<br />DateTime lastDay = today.AddDays(-(today.Day)); //last day</div><div style="font-family: Arial,Helvetica,sans-serif;">Explanation: |

1 |
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

1 |
today = today.AddMonths(1);<br />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

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

AnonymousNice code. Thanks

AnonymousThanks…

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

Anoop msIf 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!

MST : Software Company InstituteThanks for this post..

asp.net training in jaipur