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?
You can use an enum of months:
I am not 100% certain on the syntax for enum.Parse(), though.
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", ...)
andParseExact("January", ...)
should work and which should fail?That will be the difference between
CultureInfo.CurrentCulture
andCultureInfo.InvariantCulture
.If you are using c# 3.0 (or above) you can use extenders
You can use the DateTime.Parse method to get a DateTime object and then check its Month property. Do something like this:
The trick is to build a valid date to create a DateTime object.
What I did was to use SimpleDateFormat to create a format string, and parse the text to a date, and then retrieve the month from that. The code is below:
And answering this seven years after the question was asked, it is possible to do this comparison using built-in methods:
becomes
Which can be refactored into an extension method for simplicity. The following is a LINQPad example (hence the
Dump()
method calls):With output: