CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2005
    Posts
    43

    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

  2. #2
    Join Date
    Oct 2005
    Location
    Seattle, WA U.S.A.
    Posts
    353

    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
    Last edited by ThermoSight; March 31st, 2011 at 10:38 PM.

  3. #3
    Join Date
    Jun 2001
    Location
    Melbourne/Aus (C# .Net 4.0)
    Posts
    686

    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"
    Rob
    -
    Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......

  4. #4
    Join Date
    Oct 2005
    Location
    Seattle, WA U.S.A.
    Posts
    353

    Re: Date Calculations

    VERY nice, rliq !

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured