6

Is there a function in C# that can already change a Month name to it's corresponding month number? If not, should I make a method (like using 'Switch" or some loop function) that makes this possible?

I'm asking because I would like to have clean code and not make a huge mess in my code. Thanks in advance

Tscott
  • 465
  • 6
  • 21

2 Answers2

18
DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture).Month
Colin
  • 4,025
  • 21
  • 40
1

You can use :

Convert.ToDateTime(monthName + " 01, 1900").Month;

or

Array.IndexOf(DateTimeFormatInfo.CurrentInfo.MonthNames,
              monthName.ToLower(CultureInfo.CurrentCulture)) + 1;

and also

Array.FindIndex(DateTimeFormatInfo.CurrentInfo.MonthNames, 
                m => m.Equals(monthName, StringComparison.OrdinalIgnoreCase)) + 1;
Abdellah OUMGHAR
  • 3,627
  • 1
  • 11
  • 16