如何在C#中获取月份名称?

87 c# datetime

如何在C#中查找月份名称?我不想在这个月写一个巨大的switch声明或if声明int.在VB.Net中你可以使用MonthName(),但是C#呢?

Cod*_*ker 160

您可以使用CultureInfo获取月份名称.您甚至可以获得短月份名称以及其他有趣的东西.

我建议你把它们放到扩展方法中,以便稍后编写更少的代码.但是你可以随心所欲地实施.

以下是使用扩展方法执行此操作的示例:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 我可以补充说,还有一个可以使用的"InvariantInfo"属性.而且,在我看来,以下是一个更简单/可读的格式:`DateTimeFormatInfo.InvariantInfo.GetAbbreviatedMonthName(...)`或`DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(...)` (4认同)

Jon*_*eet 115

使用"MMMM"格式说明符:

string month = dateTime.ToString("MMMM");
Run Code Online (Sandbox Code Playgroud)

  • 假设你有约会.如果不是:`var month = new DateTime(1,i,1).ToString("MMMM");` (16认同)

Geo*_*ker 11

string CurrentMonth = String.Format("{0:MMMM}", DateTime.Now)
Run Code Online (Sandbox Code Playgroud)

  • 或者String.Format,实际上.Just DateTime.Now.ToString("MMMM")更简单. (5认同)

Rob*_*obV 8

如果您只想使用MonthName,则引用Microsoft.VisualBasic,它位于Microsoft.VisualBasic.DateAndTime中

//eg. Get January
String monthName = Microsoft.VisualBasic.DateAndTime.MonthName(1);
Run Code Online (Sandbox Code Playgroud)


小智 7

假设你的日期是今天.希望这对你有所帮助.

DateTime dt = DateTime.Today;

string thisMonth= dt.ToString("MMMM");

Console.WriteLine(thisMonth);
Run Code Online (Sandbox Code Playgroud)