开发者

How to return the number of a month in C# function

I want to return the number of a month and i made a function but it always returns 0

this is my code:

public int getNrMonth(String s)
    {
        int nr=0;
        if (s.Equals("Janu开发者_StackOverflow中文版ary"))
            nr = 1
        if (s.Equals("February"))
            nr = 2;
        return nr;


    }

Could someone tell me wath is wrong please? I'm beginner!


Why wouldn't you use the built in function:

DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month

Here is an example on use:

How to parse a month name (string) to an integer for comparison in C#?


It'd be better to do it like this:

switch (s.Trim().ToUpper())
{
    case "JANUARY": return 1;
    case "FEBRUARY": return 2;
    // etc.
}

return 0;

Reasons:

  1. switch is optimized to begin with (small point, but worth mentioning).
  2. Once you have the value, all the remaining if checks are pointless.
  3. Assuming you want "january" and "January" and " January " and "jaNuarY" all to return 1, the Trim() and ToUpper() calls will take care of that.


OK, you're a beginner, but you still have tools at your disposal. Set a breakpoint and step through in the debugger. Take a look at the value of s and nr as you do. Notice which if statements execute the nr = part and which you don't. Then you will understand. As it stands I don't think you pasted your real code in, because your question is missing a semi colon and might not even compile.


Try this sample:

     string value = "June";
     DateTime result;
     bool ok;
     ok = DateTime.TryParseExact(value, "MMMM",
                    CultureInfo.CurrentCulture, DateTimeStyles.None, out result);
     if ( ok )
     {
        int monthNumber = result.Month;
        Console.WriteLine(monthNumber);
     }


Why do it the simple, easy way when you can do it the long, complicated LINQ way!

    int GetMonthNumber(string month)
    {
        return System.Globalization.DateTimeFormatInfo.CurrentInfo.MonthNames
            .Select((m, i) => new { Month = m, Number = i + 1 })
            .First(m => m.Month.ToLower() == month.ToLower())
            .Number;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜