Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 484
ProfK Avatar asked Nov 24 '08 20:11

ProfK


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

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

like image 84
Yona Avatar answered Sep 25 '22 18:09

Yona


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(); 
like image 24
mmmeff Avatar answered Sep 25 '22 18:09

mmmeff