Converting month name to integer
Solution 1
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)
Solution 2
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).
Solution 3
This is old but something I was looking for, just incase someone else comes looking I came up with an easy solution....
Dim sM as String = "Jun"
Dim iM as Byte = 0
iM = Month(sM & " 1, 2020")
iM will equal 6
Mercurybullet
Updated on July 05, 2022Comments
-
Mercurybullet almost 2 years
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?
-
Mercurybullet almost 14 yearsLooks good, but I think it should be monthName inside the ParseExact.
-
phreakocious almost 14 yearsVB 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...
-
Mercurybullet almost 14 yearsI'm already using the DateTime library for other stuff, was just checking for a builtin way to do this conversion.
-
sephtian about 11 yearshi, but it give 1 digit month number, how can i get 2 digit month number?
-
bdukes about 11 years@sephtian, it gives back an
Integer
. If you want it as two digits, convert it to a string with that formatting, i.e.monthNumber.ToString("00")