Bạn có thể sử dụng CultureInfo để lấy tên tháng. Bạn thậm chí có thể nhận được tên tháng ngắn hạn cũng như những điều thú vị khác.
Tôi khuyên bạn nên đặt chúng vào các phương thức mở rộng, điều này sẽ cho phép bạn viết ít mã hơn sau này. Tuy nhiên, bạn có thể thực hiện theo cách bạn muốn.
Dưới đây là một ví dụ về cách thực hiện điều đó bằng các phương pháp mở rộng:
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);
}
}
Hi vọng điêu nay co ich!