.net 在 C# 中将整数转换为月份名称的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/218908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:22:30  来源:igfitidea点击:

Best way to turn an integer into a month name in c#?

.netparsingdate

提问by DevelopingChris

Is there a best way to turn an integer into its month name in .net?

有没有最好的方法将整数转换为 .net 中的月份名称?

Obviously I can spin up a datetime to string it and parse the month name out of there. That just seems like a gigantic waste of time.

显然我可以启动一个日期时间来将它串起来并从中解析月份名称。这似乎是在浪费时间。

回答by Nick Berardi

Try GetMonthName from DateTimeFormatInfo

从 DateTimeFormatInfo 尝试 GetMonthName

http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.getmonthname.aspx

http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.getmonthname.aspx

You can do it by:

你可以这样做:

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);

回答by leppie

Why not just use somedatetime.ToString("MMMM")?

为什么不直接使用somedatetime.ToString("MMMM")

回答by Ovidiu Pacurar

Updated with the correct namespace and object:

更新了正确的命名空间和对象:

//This was wrong
//CultureInfo.DateTimeFormat.MonthNames[index];

//Correct but keep in mind CurrentInfo could be null
DateTimeFormatInfo.CurrentInfo.MonthNames[index];

回答by Tokabi

You can use a static method from the Microsoft.VisualBasicnamespace:

您可以使用Microsoft.VisualBasic命名空间中的静态方法:

string monthName = Microsoft.VisualBasic.DateAndTime.MonthName(monthInt, false);

回答by user1534576

DateTime dt = new DateTime(year, month, day);
Response.Write(day + "-" + dt.ToString("MMMM") + "-" + year);

In this way, your month will be displayed by their name, not by integer.

这样,您的月份将按名称显示,而不是按整数显示。

回答by user1534576

To get abbreviated month value, you can use Enum.Parse();

要获得缩写的月份值,您可以使用 Enum.Parse();

Enum.Parse(typeof(Month), "0");

This will produce "Jan" as result.

这将产生“Jan”作为结果。

Remember this is zero-based index.

请记住,这是从零开始的索引。