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

标签 c# datetime formatting

请大家帮忙 我需要将日期 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

关于c# - 我如何在 c# 中格式化 07/03/2012 到 2012 年 3 月 7 日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9601593/

相关文章:

c# - asp.net中清空Cache对象的集中方式

mysql - 使用 SQL 选择动态 Unix 纪元时间

PHP 确定多个(n)日期时间范围何时相互重叠

vba - 如何在格式化十进制数字时保留尾随零?

css - 需要按钮 float 到卡片 pug/css 的底部

C# 从 LINQ 计算对象初始化期间的日期时间差异

c# - 无法将属性或索引器 'System.DateTime.TimeOfDay' 分配给 — 它是只读的

javascript - 在 Jquery 倒计时器中用当前日期时间替换硬编码日期时间

c# - 将 180 更改为 03 :00 的简单方法

c# - Entity Framework 返回数据库中不存在的实体