13

I found a lot of ways to get the name from a number but now I need it the other way around.

If the string equals April, I want to convert it to int "4".

Does anyone know the best way to accomplish this server side?

1
  • Yeah I think it is. ::face palm::
    – balexander
    Jun 9, 2011 at 18:17

3 Answers 3

29
int month = DateTime.ParseExact(MonthNameStr, "MMMM", CultureInfo.CurrentCulture ).Month

or you can do

int  month = DateTimeFormatInfo.CurrentInfo.MonthNames.ToList().IndexOf(MonthNameStr) + 1;
0
4
 int month = DateTime.ParseExact("April", "MMMM", CultureInfo.InvariantCulture).Month;
1
  • ^^ the best way to get month number from month name or Code, so if you have "DEC" in string, you will use "MMM" in the second parameter. Very nice.
    – user734028
    Dec 21, 2021 at 7:17
1

You can use the DateTime.ParseExact Method with a custom format specifier consisting only of the the "MMMM" Custom Format Specifier:

int month = DateTime.ParseExact("April", "MMMM", new CultureInfo("en-US"))
                    .Month;

Not the answer you're looking for? Browse other questions tagged or ask your own question.