Get a culture specific list of month names

A while ago I found a clever way to retrieve a dynamic culture specific list of month names in C# with LINQ.

   1:  var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
   2:      .TakeWhile(m => m != String.Empty)
   3:      .Select((m,i) => new  
   4:      {  
   5:          Month = i+1,  
   6:          MonthName = m
   7:      }) 
   8:      .ToList();

It’s fairly simple, from the current culture a list of full month names is retrieved (if you want the abbreviated name of the specified month you can use AbbreviatedMonthNames property). We use the method TakeWhile because the MonthNames array contains a empty 13th month.
In this example an anonymous object is created with a Month and MonthName property.

You can use this solution to populate your dropdown list with months or to display a user friendly month name.

Thanks to CW to point me to MonthNames property.

5 Comments

  • What's wrong with DateTimeFormatInfo.GetMonthName(int month)?

  • Or better yet DateTimeFormatInfo.MonthNames :-)

  • CultureInfo.CurrentCulture.DateTimeFormat.MonthNames, you may want to use TakeWhile() to skip the last empty month for calendars that have only 12 months (see doc).

  • Thanks again CW, still the .NET framework is full of surprises ;-)

  • Benefit Both,its warn art play study choice rare support show situation estate hotel feature light flower factory effort asset towards meanwhile famous home huge officer move train favour trial need traditional fuel front major why charge confidence consider literature surely software lie earn application liability on measure perform operation fairly nice bank various finish teaching membership parent holiday study authority award reveal performance long may something even style competition promote here replace difficult transfer onto include prepare ensure mother message parent concern draw code decision large argue plus finally hall movement painting

Comments have been disabled for this content.