-
Date Calculations
Hi I would like to display the past 12 months, excluding current month based on today's date in a dropdownlist.
e.g. today: 31/03/2011
I want to display in the list
February 2011
January 2011
December 2010
November 2010
-
-
-
March 2010
Any suggestions how this can be done.
Thanks
-
Re: Date Calculations
Something like the following might get you off to a good start ...
Code:
private void button1_Click(object sender, EventArgs e){
string tmp, month, year;
DateTime current = DateTime.Now;
for (int i = 12; i > 0; i--) {
current = current.AddMonths(-1);
tmp = current.ToLongDateString();
month = (tmp.Split(' '))[1].Trim();
year = tmp.Substring(tmp.LastIndexOf(',')+1).Trim();
listView1.Items.Add(month + ", " + year);
}
}
As you can see, I am placing the result in a listView. You'll probably want to do something else but the loop above will at least generate the strings for you. Then you can do with them as you will.
Give it a try ... might work.
OldFool
-
Re: Date Calculations
Here's one way:
Code:
List<string> myDates = new List<string>(12);
for (int i = 0; i < 12; i++)
myDates.Add((DateTime.Now.AddMonths(-i)).ToString("MMMM yyyy"));
Then bind the ItemSource of the DropDownList to myDates. I would set a variable equal to DateTime.Now, before the loop and then use that variable. Just in case somebody runs your code at 1 nanosecond before midnight on the last day of the month!
- myDates Count = 12
[0] "April 2011"
[1] "March 2011"
[2] "February 2011"
[3] "January 2011"
[4] "December 2010"
[5] "November 2010"
[6] "October 2010"
[7] "September 2010"
[8] "August 2010"
[9] "July 2010"
[10] "June 2010"
[11] "May 2010"
-
Re: Date Calculations