DevelopingChris
DevelopingChris

Reputation: 40788

Best way to turn an integer into a month name in c#?

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.

Upvotes: 125

Views: 69722

Answers (6)

Ovidiu Pacurar
Ovidiu Pacurar

Reputation: 8209

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];

Upvotes: 20

Tokabi
Tokabi

Reputation: 1024

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

string monthName = Microsoft.VisualBasic.DateAndTime.MonthName(monthInt, false);

Upvotes: 7

user1534576
user1534576

Reputation: 71

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.

Upvotes: 7

Nelson
Nelson

Reputation:

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.

Upvotes: 2

Nick Berardi
Nick Berardi

Reputation: 54854

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

Upvotes: 275

leppie
leppie

Reputation: 117220

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

Upvotes: 21

Related Questions