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?

9/6/2017 2:37:37 PM

Accepted Answer

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

1/3/2019 8:40:55 AM

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";

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow