如何获得在C#月份的名字吗? [英] How to get the month name in C#?
问题描述
如何去约在C#中找到月份的名字吗?我不想写一个巨大的开关
语句或如果
上月声明 INT
。在VB.Net你可以使用 MONTHNAME()
,但对于C#?
How does one go about finding the month name in C#? I don't want to write a huge switch
statement or if
statement on the month int
. In VB.Net you can use MonthName()
, but what about C#?
推荐答案
您可以使用的CultureInfo来获取月份名称。你甚至可以在短短的一个月的名称,以及其他有趣的事情。
You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.
我会建议你把这些进入扩展方法,这将允许您以后少写code。然而,你可以实现你喜欢的。
I would suggestion you put these into extension methods, which will allow you to write less code later. However you can implement however you like.
下面是如何使用扩展方法来做到这一点的例子:
Here is an example of how to do it using extension methods:
using System;
using System.Globalization;
class Program
{
static void Main()
{
Console.WriteLine(DateTime.Now.ToMonthName());
Console.WriteLine(DateTime.Now.ToShortMonthName());
Console.Read();
}
}
static class DateTimeExtensions
{
public static string ToMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
}
public static string ToShortMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
}
}
希望这有助于!
这篇关于如何获得在C#月份的名字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!