92

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?

H.B.
  • 166,899
  • 29
  • 327
  • 400
Alex Hope O'Connor
  • 9,354
  • 22
  • 69
  • 112

4 Answers4

167
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

CharithJ
  • 46,289
  • 20
  • 116
  • 131
38
var monthIndex = 1;
return month = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(monthIndex);

You can try this one as well

xei2k
  • 536
  • 4
  • 9
  • 5
    Just to add something to this good answer, the DateTimeFormatInfo is inside of System.Globalization, then is needed to import this namespace. – BernieSF Nov 28 '14 at 20:33
15

You can do something like this instead.

return new DateTime(2010, Month, 1).ToString("MMM");
Bala R
  • 107,317
  • 23
  • 199
  • 210
0
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");
Nerdroid
  • 13,398
  • 5
  • 58
  • 69
Samuel A
  • 57
  • 1