gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:37:56 24 4
gpt4 key购买 nike

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

最佳答案

您可以使用 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);
}
}

希望这对您有所帮助!

关于c# - 如何在 C# 中获取月份名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/975531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com