Tscott
Tscott

Reputation: 485

C# - Best way to convert Month names to their month number

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

Upvotes: 6

Views: 5720

Answers (2)

Abdellah OUMGHAR
Abdellah OUMGHAR

Reputation: 3745

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;

Upvotes: 1

Colin
Colin

Reputation: 4135

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

Upvotes: 18

Related Questions