开发者

How to get an array of months in c#

开发者 https://www.devze.com 2022-12-10 02:50 出处:网络
I want to get the month array in c开发者_如何转开发#. somthing like this : { January , February , ... , December }

I want to get the month array in c开发者_如何转开发#.

somthing like this : { January , February , ... , December }

How can I do this? please send me codes in C#. thanks


You need to careful about localization issues as well: You can use:

string[] monthNames = 
    System.Globalization.CultureInfo.CurrentCulture
        .DateTimeFormat.MonthGenitiveNames;

The genitive case is introduced in some inflected languages by a genitive noun inflection, which in non-inflected languages matches the use of the equivalent of the English preposition "of". For example, a date in the Russian (Russia), "ru-RU", culture, consists of the day number and the genitive month name.

More info…

EDIT: If you need english month names you can set your current culture as en-US

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); 


string[] monthNames = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;

foreach (string m in monthNames) // writing out
{
    Console.WriteLine(m);
}

Output:

January
February
March
April
May
June
July
August
September
October
November
December

Update:
Do note that for different locales/cultures, the output might not be in English. Haven't tested that before though.

For US English only:

string[] monthNames = (new System.Globalization.CultureInfo("en-US")).DateTimeFormat.MonthNames;


string[] months = new string[] {"January", "February", "March", "April", "May",
  "June", "July", "August", "September", "October", "November", "December"};


An alternate that hopefully teaches how you can apply the range function to create for sequential things.

var startDate = new DateTime(2014,1,1);
var months = Enumerable.Range(0,11)
                       .Select(startDate.AddMonths);
                       .Select(m => m.ToString("yyyy MMMM"))
                       .ToList();

What it is doing is creating a DateTime object (startDate) and using that object to generate all the other dates relative to itself.

  1. Enumerable.Range(0,11) creates a list of integers {0,1,2,3,4,5,6,7,8,9,10,11}

  2. Select(startDate.AddMonths) feeds each of those integers to the AddMonths function of startDate which produces a list of dates from January to December.

  3. Select(m => m.ToString("yyyy MMMM") takes each of the dates from january to december and converts them into a formatted string (in this case "2014 January")

  4. ToList() evaluates all the functions and returns it as a list of strings.

0

精彩评论

暂无评论...
验证码 换一张
取 消