Well,IFormatProvider接口是壹個格式化提供者,它僅僅提供壹個承諾,它告訴編譯器實現該了接口的類會提供具體的格式化,而真正的格式化接口是ICustomFormatter接口。所以自定義化格式化日期,我會這樣子做:
?class?Program{
static?void?Main(string[]?args)
{
String?format?=?String.Format(new?MyFormatProvider(),?"{0:CN}",?DateTime.Now);
Console.WriteLine(format);
}
}
class?MyFormatProvider?:?IFormatProvider
{
public?object?GetFormat(Type?formatType)
{
if?(formatType?==?typeof(ICustomFormatter))
{
return?new?MyCustomFormatter();
}
return?CultureInfo.CurrentCulture.GetFormat(formatType);
}
}
class?MyCustomFormatter?:?ICustomFormatter
{
public?string?Format(string?format,?object?arg,?IFormatProvider?formatProvider)
{
if?(arg?is?DateTime)
{
DateTime?dt=(DateTime)arg;
//?CN-中國,UK-英國,US-美國。這裏僅僅是壹個示例。具體用法根據實際情況而定
if?(format?==?"CN")?return?String.Format("{0}年{1}月{2}日",?dt.Year,dt.Month.ToString("##"),dt.Day);
if?(format?==?"UK")?return?String.Format("{0}/{1}/{2}",?dt.Day?,dt.Month.ToString("##"),dt.Year);
}
return?String.Format("Non-Formatter{0}",?format);
}
}