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


.Net Problem Overview

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.

.Net Solutions

Solution 1 - .Net

Try GetMonthName from DateTimeFormatInfo

You can do it by:


Solution 2 - .Net

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

Solution 3 - .Net

Updated with the correct namespace and object:

//This was wrong

//Correct but keep in mind CurrentInfo could be null

Solution 4 - .Net

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

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

Solution 5 - .Net

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.

Solution 6 - .Net

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.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDevelopingChrisView Question on Stackoverflow
Solution 1 - .NetNick BerardiView Answer on Stackoverflow
Solution 2 - .NetleppieView Answer on Stackoverflow
Solution 3 - .NetOvidiu PacurarView Answer on Stackoverflow
Solution 4 - .NetTokabiView Answer on Stackoverflow
Solution 5 - .Netuser1534576View Answer on Stackoverflow
Solution 6 - .NetNelsonView Answer on Stackoverflow