views:

106

answers:

4

I did a quick search for this and was surprised not to find it anywhere.

Basically looking to convert full month names (January, September, etc) to the equivalent number that would be used in mm/dd/yyyy format.

I can put together my own array and pull it out accordingly, but there has to be a quick and straightforward method already. Right?

+5  A: 

You can use the format string MMMM for the full name of the month.

See custom DateTime format strings on MSDN.

Dim fullMonthName as DateTime
fullMonthName = DateTime.ParseExact("26 January 2010", "dd MMMM yyyy", 
                                           CultureInfo.InvariantCulture)
Oded
+3  A: 
Dim monthName = "September"
Dim monthNumber = DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture).Month

If you are basing this on user input, I think this is the cleanest (especially if you are expecting multiple cultures to use this). DateTime.ParseExact will allow you to input any sort of input and translate it into a DateTime, then pluck off whatever part of it you care about.

If, however, this isn't have on user input, I would have to suggest using some sort of static collection (whether a dictionary or an enum).

bdukes
was going to post the exact same code...
jeroenh
Looks good, but I think it should be monthName inside the ParseExact.
Mercurybullet
@Mercurybullet thanks, fixed.
bdukes
A: 

Call me crazy, but isn't this exactly what an enum is for? Maybe worth considering to keep the code as simple as possible. http://visualbasic.about.com/od/usingvbnet/a/enum01.htm

phreakocious
You're crazy :P
Neil N
VB is not my specialty, but in general, I wouldn't add an extra library solely to translate 12 strings into numbers. Maybe if there were some other useful functions there...
phreakocious
I'm already using the DateTime library for other stuff, was just checking for a builtin way to do this conversion.
Mercurybullet
Then you are rockin! =)
phreakocious
A: 

This may sound long winded, why not use an IF Statement or Select Case.

If Month = "January" Then MonthNum = "1"
Else If Month = "February" Then .......
Connnnoorr