Converting Month Abbreviations to Month Numbers
Posted
Thu, Aug 13 2009 16:20
by
Deborah Kurata
If you are working with months and need to convert a month name to a month number, such as Feb to 02 or Sep to 09, you can use the following code.
NOTE: Be sure to set a reference to System.Globalization.
In C#:
private string GetMonthNumberFromAbbreviation(string mmm)
{
string[] monthAbbrev =
CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames;
int index = Array.IndexOf(monthAbbrev, mmm) + 1;
return index.ToString("0#");
}
In VB:
Private Function GetMonthNumberFromAbbreviation(ByVal mmm As String) _
As String
Dim monthAbbrev As String() = _
CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames
Dim index As Integer = Array.IndexOf(monthAbbrev, mmm) + 1
Return index.ToString("0#")
End Function
This function uses the CultureInfo class to get the correct set of month abbreviations based on the user’s current culture.
It then uses IndexOf to find the month entry in the array. Since the resulting monthAbbrev is 0-based, the code adds 1 to the index.
It then uses custom numeric string formatting to format the number as two digits.
You call this code as follows:
In C#:
string num = GetMonthNumberFromAbbreviation("Dec");
In VB:
Dim num As String = GetMonthNumberFromAbbreviation("Dec")
Enjoy!