posted 7/21/2010 by Hajan Selmani
This is pretty simple, but a bit tricky for those that haven't tried it yet, so I would like to document it here :).
You may be in need to calculate the first or last day of the month in your ASP.NET application.
The method is simple (but still tricky for beginners).
Here is the code
DateTime dateNow = DateTime.Now; //create DateTime with current date string firstDayDate = dateNow.AddDays(-(dateNow.Day - 1)).ToString(); //first day dateNow = dateNow.AddMonths(1); string lastDay = dateNow.AddDays(-(dateNow.Day)).ToString(); //last day
Explanation:
DateTime dateNow = DateTime.Now;
With this line we are creating new DateTime object with name dateNow - if you go over it in debugging mode, the value (right now) is: {21-07-2010 17:27:50} - wich means current date time shown in the local format you've specified in your Regional Settings.
next line
string firstDayDate = dateNow.AddDays(-(dateNow.Day - 1)).ToString();
Here I am assigning the date to string, you can of course assign it to DateTime - just you will need to remove the ToString() conversion method.So, here I'm using the AddDays method which can add given number of days to the current date. Using dateNow.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).
-(dateNow.Day - 1) is actually -(21-1) = 01-07-2010 17:27:50
Next, the calculation of the LastDay
dateNow = dateNow.AddMonths(1); string lastDay = dateNow.AddDays(-(dateNow.Day)).ToString(); //last day
With dateNow = dateNow.AddMonths(1) I'm adding one month plus to the current date.
Before adding, the dateNow value was {21-07-2010 17:27:50} - after adding +1 month, the dateNow 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 dateNow.Day integer value. We do not add dateNow.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
I hope this was useful for you...
All the best,Hajan
That code was just the thing I was looking for! Thanks
This comment is awaiting moderation.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18