How to list all month names, e.g. for a combo?
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 use the following to return an array of string containing the month names
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
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();
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]);
}