2011-06-09 23 views
56

Simplemente estaba tratando de usar la estructura DateTime para transformar un número entero entre 1 y 12 en un nombre de mes abbrieviated.Convertir mes en mes nombre

Aquí es lo que he intentado:

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

Sin embargo me siento un FormatException en la primera línea debido a que la cadena no es un válido DateTime. ¿Puede alguien decirme cómo hacer esto?

Respuesta

96
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1); 

Ver Here para más detalles.

O

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

O si desea obtener el nombre específico de la cultura abreviada.

GetAbbreviatedMonthName(1); 

Reference

+7

'GetAbbreviatedMonthName()' parece apropiado. –

+0

¿Qué es lo opuesto a esto? ingresar el nombre del mes y recuperar el número? –

+0

'int month = DateTime.ParseExact (MonthNameValue," MMMM ", CultureInfo.CurrentCulture) .Month' – CharithJ

10

Puede hacer algo como esto en su lugar.

return new DateTime(2010, Month, 1).ToString("MMM"); 
21
var monthIndex = 1; 
return month = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(monthIndex); 

Puede probar esto, así

+4

Solo para agregar algo a esta buena respuesta, DateTimeFormatInfo está dentro de System.Globalization, luego se necesita para importar este espacio de nombres. – BernieSF

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