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