How to parse a month name (string) to an integer for comparison in C#?

spilliton picture spilliton · Nov 3, 2008 · Viewed 137.6k times · Source

I need to be able to compare some month names I have in an array.

It would be nice if there were some direct way like:

Month.toInt("January") > Month.toInt("May")

My Google searching seems to suggest the only way is to write your own method, but this seems like a common enough problem that I would think it would have been already implemented in .Net, anyone done this before?

Answer

James Curran picture James Curran · Nov 3, 2008

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

Although, for your purposes, you'll probably be better off just creating a Dictionary<string, int> mapping the month's name to its value.