收录日期:2020/11/30 16:10:05 时间:2010-09-07 20:09:53 标签:vb.net,datetime,date,integer

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?

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)
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).

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

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 .......