How to program a var to iterate throgh the values...

I need a var to iterate through:

DateTime.Now.ToString("MM"), down 6 months.

If now is january I need:
"01"
"12"
...
"07"


RahnAsked:
Who is Participating?
 
infochandruCommented:
Hope this will help

        for (int i = 0; i < 7; i++)
        {
            lblTest.Text += DateTime.Now.AddMonths(-i).ToString("MM") + "<br>";
        }
0
 
zadeveloperCommented:

var StartDate = DateTime.Now;
            for (var i = 0; i < 6; i++)
            {
                System.Diagnostics.Debug.Print(StartDate.AddMonths(-1*i).ToString("MM"));
            }

Open in new window

0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
Meir RivkinFull stack Software EngineerCommented:
check this code snippet.
the function get 3 params:
1 - inital month (from DateTime.Now.ToString("MM"))
2 - number of months to subtract in each iteration
3 - number of iterations
static void Main(string[] args)
        {
            string str = DateTime.Now.ToString("MM");
            int resMonth = IterateDownMonth(int.Parse(str), 7, 8);
        }

        static int IterateDownMonth(int initMonth, int subMonths, int iterations)
        {
            while (iterations-- > 0)
            {
                initMonth -= subMonths;
                initMonth = initMonth > 0 ? initMonth : initMonth + 12;
            }

            return initMonth;
        }

Open in new window

0
 
Roshan DavisCommented:

DateTime dt = DateTime.Now
for(int i = 0 ; i <6; i++)
{
       string strDisplay = dt.AddMonths(-i).ToString("MM");
}

Open in new window

0
 
zadeveloperCommented:
so pretty much all the same thing :)
0
 
RahnAuthor Commented:
this for loop presents:
01
12
10
7
3
....

   for (int i = 0; i < 7; i++)
        {
            lblTest.Text += DateTime.Now.AddMonths(-1).ToString("MM") + "
";
        }
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.