Home » c# » How to list all month names, e.g. for a combo?

How to list all month names, e.g. for a combo?

Posted by: admin November 29, 2017 Leave a comment

Questions:

At the moment I’m creating a DateTime for each month and formatting it to only include the month.
Is there another or any better way to do this?

Answers:

You can use the DateTimeFormatInfo to get that information:

// Will return January
string name = DateTimeFormatInfo.CurrentInfo.GetMonthName(1);

or to get all names:

string[] names = DateTimeFormatInfo.CurrentInfo.MonthNames;

You can also instantiate a new DateTimeFormatInfo based on a CultureInfo with DateTimeFormatInfo.GetInstance or you can use the current culture’s CultureInfo.DateTimeFormat property.

Keep in mind that calendars in .Net support up to 13 months, thus you will get an extra empty string at the end for calendars with only 12 months (such as those found in en-US or fr for example).

Questions:
Answers:

You can use the following to return an array of string containing the month names

System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames

Questions:
Answers:

This method will allow you to apply a list of key value pairs of months to their int counterparts. We generate it with a single line using Enumerable Ranges and LINQ. Hooray, LINQ code-golfing!

var months = Enumerable.Range(1, 12).Select(i => new { I = i, M = DateTimeFormatInfo.CurrentInfo.GetMonthName(i) });

To apply it to an ASP dropdown list:

// <asp:DropDownList runat="server" ID="ddlMonths" />
ddlMonths.DataSource = months;
ddlMonths.DataTextField = "M";
ddlMonths.DataValueField = "I";
ddlMonths.DataBind();

Questions:
Answers:

They’re defined as an array in the Globalization namespaces.

using System.Globalization;

for (int i = 0; i < 12; i++) {
   Console.WriteLine(CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[i]);
}

Questions:
Answers:

Try enumerating the month names:

for( int i = 1; i <= 12; i++ ){
  combo.Items.Add(CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[i]);
}

It’s in the System.Globalization namespace.

Hope that helps!

Questions:
Answers:

You can get a list of localized months from Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames and invariant months from DateTimeFormatInfo.InvariantInfo.MonthNames.

string[] localizedMonths = Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames;
string[] invariantMonths = DateTimeFormatInfo.InvariantInfo.MonthNames;

for( int month = 0; month < 12; month++ )
{
    ListItem monthListItem = new ListItem( localizedMonths[month], invariantMonths[month] );
    monthsDropDown.Items.Add( monthListItem );
}

There might be some issue with the number of months in a year depending on the calendar type, but I’ve just assumed 12 months in this example.

Questions:
Answers:
public IEnumerable<SelectListItem> Months
{
  get
  {
    return Enumerable.Range(1, 12).Select(x => new SelectListItem
    {
      Value = x.ToString(),
      Text = DateTimeFormatInfo.CurrentInfo.GetMonthName(x)
    });
  }
}

Questions:
Answers:

A way to retrieve a dynamic culture specific list of month names in C# with LINQ.

ComboBoxName.ItemsSource= 
System.Globalization.CultureInfo.
CurrentCulture.DateTimeFormat.MonthNames.
TakeWhile(m => m != String.Empty).ToList();

OR

In this example an anonymous object is created with a Month and MonthName property

var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
 .TakeWhile(m => m != String.Empty)
 .Select((m,i) => new  
 {  
     Month = i+1,  
     MonthName = m
 }) 
 .ToList();

PS: We use the method TakeWhile because the MonthNames array contains a empty 13th month.

Questions:
Answers:

A little LINQ just because it is beautifully concise:

var monthOptions = DateTimeFormatInfo.CurrentInfo.MonthNames
    .Where(p=>!string.IsNullOrEmpty(p))
    .Select((item, index) => new { Id = index + 1, Name = item });

You need the Where clause because the calendar returns a 13th month name (empty in English).

The index returns index within the IEnumerable, so you need a +1 for the actual month index.

Questions:
Answers:
List<string> mnt = new List<string>();    
int monthCount = Convert.ToInt32(cbYear.Text) == DateTime.Now.Year ? DateTime.Now.Month : 12;    
            for (int i = 0; i < monthCount; i++)    
            {    
                mnt.Add(CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[i]);    
            }    
            cbMonth.DataSource = mnt;

Questions:
Answers:
string[] monthNames = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;

foreach (string m in monthNames) // writing out
{
    Console.WriteLine(m);
}

Output:

January
February
March
April
May
June
July
August
September
October
November
December

Update:
Do note that for different locales/cultures, the output might not be in English. Haven’t tested that before though.

For US English only:

string[] monthNames = (new System.Globalization.CultureInfo("en-US")).DateTimeFormat.MonthNames;

Questions:
Answers:

Here is a good example for filling a drop down list with Months for Credit Card form:

    Dim currentCulture As CultureInfo = CultureInfo.CurrentUICulture
    Dim monthName, monthNumber As String

    For x As Integer = 0 To 11
        monthNumber = (x + 1).ToString("D2")
        monthName = currentCulture.DateTimeFormat.MonthNames(x)
        Dim month As New ListItem(String.Format("{0} - {1}", monthNumber, monthName),
                                  x.ToString("D2"))
        ddl_expirymonth.Items.Add(month)
    Next

Creates the following localized to current language, example:

01 - January
02 - February
etc.

Leave a Reply

Your email address will not be published. Required fields are marked *