c# - 我如何在 c# 中格式化 07/03/2012 到 2012 年 3 月 7 日

请大家帮忙 我需要将日期 03/03/2012 显示为 March 3rd,2012 等

最佳答案

您可以创建自己的自定义格式提供程序来执行此操作:

public class MyCustomDateProvider: IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;

        return null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (!(arg is DateTime)) throw new NotSupportedException();

        var dt = (DateTime) arg;

        string suffix;

        if (new[] {11, 12, 13}.Contains(dt.Day))
        {
            suffix = "th";
        }
        else if (dt.Day % 10 == 1)
        {
            suffix = "st";
        }
        else if (dt.Day % 10 == 2)
        {
            suffix = "nd";
        }
        else if (dt.Day % 10 == 3)
        {
            suffix = "rd";
        }
        else
        {
            suffix = "th";
        }

        return string.Format("{0:MMMM} {1}{2}, {0:yyyy}", arg, dt.Day, suffix);
    }
}

然后可以这样调用:

var formattedDate = string.Format(new MyCustomDateProvider(), "{0}", date);

导致(例如):

March 3rd, 2012

https://stackoverflow.com/questions/9601593/

相关文章:

java - 日期和时间格式取决于区域设置

asp.net - 如何在 ASP.NET RadioButtonList 中的项目之间添加空格

javascript - 如何设置 VSCode 以将花括号放在新行上?

java - 如何使用 Java 的 DecimalFormat 进行 "smart"货币格式?

python - 以元组为参数的新样式格式

xml - 如何在 sublime 3 中安装 sublime text indent xml

java - 使用 Java 将电话号码转换为国际格式 (E.164) 的最佳方法是什么?

Java - 将双值格式化为美元金额

formatting - excel中的数字格式: Showing % value without

objective-c - 将 ISO 8601 转换为 NSDate