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

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?

80037 次浏览

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

System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames

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.

var dateFormatInfo = CultureInfo.GetCultureInfo("en-GB").DateTimeFormat;

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).

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.

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!

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]);
}
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;

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();
public IEnumerable<SelectListItem> Months
{
get
{
return Enumerable.Range(1, 12).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = DateTimeFormatInfo.CurrentInfo.GetMonthName(x)
});
}
}

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.

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.

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.

How to create a custom list of month names in any order

Yes, I'm answering a question from over 10 years ago! :D

Yet, I wanted to add this code snippet on the chance it might help others. It shows how to output a list of month names in any custom order. In my case I needed it to start in October, but you could put the months in any sequence (even have repeating months) by setting the list of integers.

model.Controls = new
{
FiscalMonths = new
{
Value = DateTime.Now.Month,
Options = (new List<int> { 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9 }).Select(p => new
{
Value = p,
Text = DateTimeFormatInfo.CurrentInfo.GetMonthName(p)
})
}
};

And the json output for use in a dropdown:

  "FiscalMonths": {
"Value": 10,
"Options": [
{
"Value": 10,
"Text": "October"
},
{
"Value": 11,
"Text": "November"
},
{
"Value": 12,
"Text": "December"
},
{
"Value": 1,
"Text": "January"
},
{
"Value": 2,
"Text": "February"
},
etc ....

Sure, I'll give my input to a 10+ year old question.

In my case, I create a property that returns a dictionary (or similar), generated with the following code:

Dictionary<int, string> Months = Enumerable.Range(1, 12).Select(i => new KeyValuePair<int, string>(i, System.Globalization.DateTimeFormatInfo.CurrentInfo.GetMonthName(i))).ToDictionary(x => x.Key, x => x.Value);

Output (from Linqpad):

Key Value
1   January
2   February
3   March
4   April
5   May
6   June
7   July
8   August
9   September
10  October
11  November
12  December

Hope somebody finds this useful!

I did in the following way: (it's possible to set the culture)

var months = Enumerable.Range(1, 12).Select(i =>
new
{
Index = i,
MonthName = new CultureInfo("en-US").DateTimeFormat.GetAbbreviatedMonthName(i)
})
.ToDictionary(x => x.Index, x => x.MonthName);

You can easily do something like below with linq so that you only have 12 items in your drop down.

var Months = new SelectList((DateTimeFormatInfo.CurrentInfo.MonthNames).Take(12));