Sre*_*kat 30 c# formatting datetime
任何人请帮助我需要显示日期03/03/2012作为2012年3月3日等
Rob*_*ine 48
您可以创建自己的自定义格式提供程序来执行此操作:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以这样调用:
var formattedDate = string.Format(new MyCustomDateProvider(), "{0}", date);
Run Code Online (Sandbox Code Playgroud)
导致(例如):
2012年3月3日
reg*_*bsb 29
Humanizer满足您操作和显示字符串,枚举,日期,时间,时间跨度,数字和数量的所有.NET需求
要安装Humanizer,请在程序包管理器控制台中运行以下命令
PM> Install-Package Humanizer
Run Code Online (Sandbox Code Playgroud)
Ordinalize将一个数字转换为一个序数字符串,用于表示有序序列中的位置,如第1,第2,第3,第4:
1.Ordinalize() => "1st"
5.Ordinalize() => "5th"
Run Code Online (Sandbox Code Playgroud)
然后你可以使用:
String.Format("{0} {1:MMMM yyyy}", date.Day.Ordinalize(), date)
Run Code Online (Sandbox Code Playgroud)
CD.*_*D.. 11
date.ToString("MMMM d, yyyy")
Run Code Online (Sandbox Code Playgroud)
或者如果你也需要"rd":
string.Format("{0} {1}, {2}", date.ToString("MMMM"), date.Day.Ordinal(), date.ToString("yyyy"))
Run Code Online (Sandbox Code Playgroud)
Ordinal()
方法可以发现这里