views:

7455

answers:

7

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?

A: 

If you are using c# 3.0 (or above) you can use extenders

Adam Naylor
I'm using .net 2.0
spilliton
Then yep, unfortunatly i think your own method would be the most elegant solution.
Adam Naylor
+27  A: 

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.

James Curran
Be sure to consider http://stackoverflow.com/questions/258793/how-to-parse-a-month-name-string-to-an-integer-for-comparison-in-c#258895 when deciding whether to use CultureInfo.CurrentCulture or CultureInfo.InvariantCulture
Rasmus Faber
+2  A: 

You could do something like this:

Convert.ToDate(month + " 01, 1900").Month
Aaron Palmer
+1  A: 

You can use the DateTime.Parse method to get a DateTime object and then check its Month property. Do something like this:

int month = DateTime.Parse("1." + monthName + " 2008").Month;

The trick is to build a valid date to create a DateTime object.

Rune Grimstad
+3  A: 

You can use an enum of months:

public enum Month
{
    January,
    February,
    // (...)
    December,
}    

public Month ToInt(Month Input)
{
    return (Month)Enum.Parse(typeof(Month), Input, true));
}

I am not 100% certain on the syntax for enum.Parse(), though.

Treb
It would need to be "public Month ToInt(string Input) {...}" but otherwise it is correct.
James Curran
+4  A: 

If you use the DateTime.ParseExact()-method that several people have suggested, you should carefully consider what you want to happen when the application runs in a non-English environment!

In Denmark, which of ParseExact("Januar", ...) and ParseExact("January", ...) should work and which should fail?

That will be the difference between CultureInfo.CurrentCulture and CultureInfo.InvariantCulture.

Rasmus Faber
+2  A: 

IMHO, this is a great example of one of the conundrums of programming. By taking the time to post here, you have spent several times the minute or so it would have taken to write the simple conversion function from scratch. On the other hand, by doing it yourself and showing that you did not know you could use the built in parsing function, you would leave yourself open to criticism. Damned if you do, and damned if you don't.

The lesson is: don't take criticism over trivialities too seriously.

SeaDrive