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?

balexander
  • 23,131
  • 14
  • 45
  • 68

3 Answers3

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

or you can do

int  month = DateTimeFormatInfo.CurrentInfo.MonthNames.ToList().IndexOf(MonthNameStr) + 1;
Bala R
  • 107,317
  • 23
  • 199
  • 210
4
 int month = DateTime.ParseExact("April", "MMMM", CultureInfo.InvariantCulture).Month;
cichy
  • 10,464
  • 4
  • 26
  • 36
  • ^^ 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 '21 at 07: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;
dtb
  • 213,145
  • 36
  • 401
  • 431