125

Is there a best way to turn an integer into its month name in .net?

Obviously I can spin up a datetime to string it and parse the month name out of there. That just seems like a gigantic waste of time.

DevelopingChris
  • 39,797
  • 30
  • 87
  • 118
  • Does this answer your question? [Get Month name from month number](https://stackoverflow.com/questions/3184121/get-month-name-from-month-number) – StayOnTarget Jul 08 '21 at 14:03

6 Answers6

275

Try GetMonthName from DateTimeFormatInfo

http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.getmonthname.aspx

You can do it by:

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);
Nick Berardi
  • 54,393
  • 15
  • 113
  • 135
21

Why not just use somedatetime.ToString("MMMM")?

leppie
  • 115,091
  • 17
  • 196
  • 297
  • 1
    So anytime I need to turn 1 into January, I need to new up a date time with an arbitrary year and day, in order to just get January? – DevelopingChris Oct 20 '08 at 15:56
  • 1
    That is correct, as a bonus, you can have it in any localizable language you want :) – leppie Oct 20 '08 at 15:57
20

Updated with the correct namespace and object:

//This was wrong
//CultureInfo.DateTimeFormat.MonthNames[index];

//Correct but keep in mind CurrentInfo could be null
DateTimeFormatInfo.CurrentInfo.MonthNames[index];
Bronumski
  • 14,009
  • 6
  • 49
  • 77
Ovidiu Pacurar
  • 8,173
  • 2
  • 30
  • 36
  • 1
    This doesn't work. Nick Berardi provided the correct answer. – raven Oct 20 '08 at 16:58
  • 1
    from now I will try to compile my answers first – Ovidiu Pacurar Oct 20 '08 at 18:19
  • Realizing this is an old question, I still want to point out that the accepted answer provided by Nick Berandi is more correct (at least for Microsoft's implementation - not sure about Mono), because the MonthNames property always clones the array of month names, making the whole thing a tad less efficient. – AASoft Jul 09 '13 at 22:00
7
DateTime dt = new DateTime(year, month, day);
Response.Write(day + "-" + dt.ToString("MMMM") + "-" + year);

In this way, your month will be displayed by their name, not by integer.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
user1534576
  • 71
  • 1
  • 1
7

You can use a static method from the Microsoft.VisualBasic namespace:

string monthName = Microsoft.VisualBasic.DateAndTime.MonthName(monthInt, false);
Druid
  • 6,423
  • 4
  • 41
  • 56
Tokabi
  • 1,024
  • 10
  • 12
2

To get abbreviated month value, you can use Enum.Parse();

Enum.Parse(typeof(Month), "0");

This will produce "Jan" as result.

Remember this is zero-based index.

sth
  • 222,467
  • 53
  • 283
  • 367