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

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

185552 次浏览

Use the "MMMM" format specifier:

string month = dateTime.ToString("MMMM");

You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.

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);
}
}

Hope this helps!

string CurrentMonth = String.Format("{0:MMMM}", DateTime.Now)

If you just want to use MonthName then reference Microsoft.VisualBasic and it's in Microsoft.VisualBasic.DateAndTime

//eg. Get January
String monthName = Microsoft.VisualBasic.DateAndTime.MonthName(1);

Supposing your date is today. Hope this helps you.

DateTime dt = DateTime.Today;


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


Console.WriteLine(thisMonth);
    private string MonthName(int m)
{
string res;
switch (m)
{
case 1:
res="Ene";
break;
case 2:
res = "Feb";
break;
case 3:
res = "Mar";
break;
case 4:
res = "Abr";
break;
case 5:
res = "May";
break;
case 6:
res = "Jun";
break;
case 7:
res = "Jul";
break;
case 8:
res = "Ago";
break;
case 9:
res = "Sep";
break;
case 10:
res = "Oct";
break;
case 11:
res = "Nov";
break;
case 12:
res = "Dic";
break;
default:
res = "Nulo";
break;
}
return res;
}