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