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!

Filed under: , , ,

Comments

# re: Converting Month Abbreviations to Month Numbers

Friday, August 14, 2009 11:39 AM by Mark Wisecarver

Awesome. You are soooo very much appreciated. Thanks again.

# Converting Month Abbreviations to Month Numbers - Deborah Kurata

Friday, August 14, 2009 2:04 PM by DotNetShoutout

Thank you for submitting this cool story - Trackback from DotNetShoutout

# re: Converting Month Abbreviations to Month Numbers

Monday, July 16, 2012 2:00 PM by Alf

Your sample code has nothing to do with month abbreviations. Do you understand what month abbreviation is?

# re: Converting Month Abbreviations to Month Numbers

Sunday, July 22, 2012 6:33 PM by Deborah Kurata

Can you clarify?

# re: Converting Month Abbreviations to Month Numbers

Friday, October 26, 2012 8:23 AM by sagar

salute to u sir,,,,,,,,i spend 1 days for given Solution,,,after coming to ur TechArea i got complete solution.....Thanks lot sir

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: