Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 950
Tscott Avatar asked May 03 '16 22:05

Tscott


2 Answers

DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture).Month
like image 66
Colin Avatar answered Sep 30 '22 01:09

Colin


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;
like image 29
Abdellah OUMGHAR Avatar answered Sep 30 '22 01:09

Abdellah OUMGHAR