Christian Andersen
Christian Andersen

Reputation: 9

Month showing up twice in list of months

I'm attempting to get my website to output a list with all the months in a year, but I've hit a bottleneck that I can't figure out. For some reason, October comes up twice in the list and April doesn't even come up, like this (the names are in Danish, but you can hopefully understand it):

Currently I'm getting all the months out through a foreach loop. Måneder is just a list I created earlier up on the page. It seems like for some reason when it hits the tenth, it does the addition in some weird fashion, instead of just overwriting, making it the 16th in the order instead of the 10th:

foreach (int l in Måneder)
{
    DateTime bleh = DateTime.Now.AddMonths(l);
    string blah = (bleh.ToString("MMMM"));
    Literal4.Text += blah + l + "<br/>";
}

Upvotes: 0

Views: 73

Answers (2)

Michael Liu
Michael Liu

Reputation: 55339

The problem is the loop that populates Måneder:

for (int t = 1; t <= 12; t++)
{
    int months = int.Parse(DateTime.Now.Month.ToString(t.ToString())); // <-- BUG
    Måneder.Add(months);
}

This loop gets the current month (6 for June if you run it today) and calls ToString on that number twelve times, passing the loop variable t as the format string:

6.ToString("1") ==> 1
6.ToString("2") ==> 2
6.ToString("3") ==> 3
6.ToString("4") ==> 4
6.ToString("5") ==> 5
6.ToString("6") ==> 6
6.ToString("7") ==> 7
6.ToString("8") ==> 8
6.ToString("9") ==> 9
6.ToString("10") ==> 16
6.ToString("11") ==> 11
6.ToString("12") ==> 12

Notice that 6.ToString("10") returns 16. As documented under Custom Numeric Format Strings, a 0 in a format string is actually a placeholder for a digit in the value being formatted — the value in this case being 6. The other digits 1 through 9 in a format string have no special meaning.

Why does this loop use DateTime.Now.Month at all? To build a list of numbers from 1 to 12, just call Måneder.Add(t):

for (int t = 1; t <= 12; t++)
{
    Måneder.Add(t);
}

You can also eliminate the list entirely:

for (int t = 1; t <= 12; t++)
{
    DateTime bleh = DateTime.Now.AddMonths(t);
    string blah = (bleh.ToString("MMMM"));
    Literal4.Text += blah + t + "<br/>";
}

Upvotes: 2

Robert Columbia
Robert Columbia

Reputation: 6408

The + operator does both integer addition and string concatenation. Your problem is probably that it is doing the wrong one.

Try this:

foreach (int l in Måneder)
        {
            DateTime bleh = DateTime.Now.AddMonths(l);
            string blah = (bleh.ToString("MMMM"));
           Literal4.Text += blah +  l.ToString() + "<br/>";

        }

Upvotes: 1

Related Questions