将month int转换为month name

本文关键字:month name int 转换 | 更新日期: 2023-09-27 17:58:47

我只是想使用DateTime结构将1到12之间的整数转换为缩写的月份名称。

以下是我尝试过的:

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

但是,我在第一行得到一个FormatException,因为该字符串不是有效的DateTime。有人能告诉我怎么做吗?

将month int转换为month name

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);

请参阅此处了解更多详细信息。

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

或者,如果您想获得特定于区域性的缩写名称。

GetAbbreviatedMonthName(1);

参考

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

你也可以试试这个

您可以这样做。

return new DateTime(2010, Month, 1).ToString("MMM");
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");