問題描述
如何在 C# 中獲取月份名稱? (How to get the month name in 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#?
‑‑‑‑‑
參考解法
方法 1:
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!
方法 2:
Use the "MMMM" format specifier:
string month = dateTime.ToString("MMMM");
方法 3:
string CurrentMonth = String.Format("{0:MMMM}", DateTime.Now)
方法 4:
Supposing your date is today. Hope this helps you.
DateTime dt = DateTime.Today;
string thisMonth= dt.ToString("MMMM");
Console.WriteLine(thisMonth);
方法 5:
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);
(by Abdul Gangra、CodeLikeBeaker、Jon Skeet、George Stocker、Binamra、RobV)