Convert month int to month name

C#.NetDatetime.Net 4.0

C# Problem Overview


I was simply trying to use the DateTime structure to transform an integer between 1 and 12 into an abbrieviated month name.

Here is what I tried:

DateTime getMonth = DateTime.ParseExact(Month.ToString(), 
                       "M", CultureInfo.CurrentCulture);
return getMonth.ToString("MMM");

However I get a FormatException on the first line because the string is not a valid DateTime. Can anyone tell me how to do this?

C# Solutions


Solution 1 - C#

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);

See Here for more details.

Or

DateTime dt = DateTime.Now;
Console.WriteLine( dt.ToString( "MMMM" ) );

Or if you want to get the culture-specific abbreviated name.

GetAbbreviatedMonthName(1);

Reference

Solution 2 - C#

var monthIndex = 1;
return month = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(monthIndex);

You can try this one as well

Solution 3 - C#

You can do something like this instead.

return new DateTime(2010, Month, 1).ToString("MMM");

Solution 4 - C#

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(
    Convert.ToInt32(e.Row.Cells[7].Text.Substring(3,2))).Substring(0,3) 
    + "-" 
    + Convert.ToDateTime(e.Row.Cells[7].Text).ToString("yyyy");

Attributions

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
QuestionAlex Hope O'ConnorView Question on Stackoverflow
Solution 1 - C#CharithJView Answer on Stackoverflow
Solution 2 - C#xei2kView Answer on Stackoverflow
Solution 3 - C#Bala RView Answer on Stackoverflow
Solution 4 - C#Samuel AView Answer on Stackoverflow