将月份int转换为月份名称

Ale*_*nor 70 .net c# datetime .net-4.0

我只是试图使用该DateTime结构将1到12之间的整数转换为一个明确的月份名称.

这是我尝试过的:

DateTime getMonth = DateTime.ParseExact(Month.ToString(), 
                       "M", CultureInfo.CurrentCulture);
return getMonth.ToString("MMM");
Run Code Online (Sandbox Code Playgroud)

但是我得到了FormatException第一行,因为字符串不是有效的DateTime.谁能告诉我怎么做?

Cha*_*thJ 124

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此处

要么

DateTime dt = DateTime.Now;
Console.WriteLine( dt.ToString( "MMMM" ) );
Run Code Online (Sandbox Code Playgroud)

或者,如果您想获得特定于文化的缩写名称.

GetAbbreviatedMonthName(1);
Run Code Online (Sandbox Code Playgroud)

参考

  • `GetAbbreviatedMonthName()`似乎合适. (8认同)

xei*_*i2k 26

var monthIndex = 1;
return month = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(monthIndex);
Run Code Online (Sandbox Code Playgroud)

你也可以尝试这个

  • 只是为了给这个好答案添加一些内容,DateTimeFormatInfo在System.Globalization中,然后需要导入这个命名空间. (4认同)

Bal*_*a R 11

你可以做这样的事情.

return new DateTime(2010, Month, 1).ToString("MMM");
Run Code Online (Sandbox Code Playgroud)