2011-06-09 101 views
56

我只是试图使用DateTime结构将1到12之间的整数转换为abbrieviated月份名称。将月份int转换为月份名称

这里是我的尝试:

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

但是我得到了FormatException第一线,因为该字符串不是一个有效的DateTime。谁能告诉我如何做到这一点?

回答

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

详情请参阅Here

或者

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

或者,如果你想要得到的特定文化简称名。

GetAbbreviatedMonthName(1); 

Reference

+7

'GetAbbreviatedMonthName()'似乎是适当的。 – 2011-06-09 00:43:54

+0

与此相反的是什么?输入月份名称并取回数字? – 2016-10-27 13:56:39

+0

'int month = DateTime.ParseExact(MonthNameValue,“MMMM”,CultureInfo.CurrentCulture).Month' – CharithJ 2016-10-28 02:55:53

10

你可以这样做。

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

你可以试试这一个,以及

+4

只需向此良好答案添加内容,DateTimeFormatInfo位于System.Globalization内部,则需要导入此名称空间。 – BernieSF 2014-11-28 20:33:43

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"); 
相关问题