如何创建和使用自定义的IFormatProvider的日期时间? [英] How to create and use a custom IFormatProvider for DateTime?
问题描述
我试图创建一个能够认识到自定义格式字符串为datetime对象的的IFormatProvider
的实施。下面是我实现的:
I was trying to create an IFormatProvider
implementation that would recognize custom format strings for DateTime objects. Here is my implementation:
public class MyDateFormatProvider : 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 == null) throw new ArgumentNullException("arg");
if (arg.GetType() != typeof(DateTime)) return arg.ToString();
DateTime date = (DateTime)arg;
switch(format)
{
case "mycustomformat":
switch(CultureInfo.CurrentCulture.Name)
{
case "en-GB":
return date.ToString("ddd dd MMM");
default:
return date.ToString("ddd MMM dd");
}
default:
throw new FormatException();
}
}
我期待能够用它在则DateTime.ToString(字符串格式,提供的IFormatProvider)
法像这样,而是:
DateTime d = new DateTime(2000, 1, 2);
string s = d.ToString("mycustomformat", new MyDateFormatProvider());
在这个例子中,在美国文化上运行,其结果是00cu0Ao00or0aA
,显然是因为标准DateTime格式字符串是间preTED。
In that example, running in the US Culture, the result is "00cu0Ao00or0aA"
, apparently because the standard DateTime format strings are being interpreted.
然而,当我使用相同的类以下列方式:
However, when I use the same class in the following way:
DateTime d = new DateTime(2000, 1, 2);
string s = String.Format(new MyDateFormatProvider(), "{0:mycustomformat}", d);
我得到了我期望的,即太阳报02年1月
我不明白了不同的结果。可能有人解释一下吗?
I don't understand the different results. Could someone explain?
谢谢!
推荐答案
检查则DateTime.ToString
方法,反射显示,的DateTime
结构采用 DateTimeFormatInfo.GetInstance
方法来获得用于格式化的提供者。在 DateTimeFormatInfo.GetInstance
请求类型的格式的DateTimeFormatInfo
从供应商传递,从不为 ICustomFormmater
,所以它只返回的的DateTimeFormatInfo
或的CultureInfo
如果没有供应商是一个实例找到。看来,则DateTime.ToString
方法不兑现 ICustomFormatter
接口,如的StringBuilder。格式
方法做,因为你的的String.Format
示例所示。
Checking the DateTime.ToString
method with Reflector shows that the DateTime
structure uses the DateTimeFormatInfo.GetInstance
method to get the provider to be used for formatting. The DateTimeFormatInfo.GetInstance
requests a formatter of type DateTimeFormatInfo
from the provider passed in, never for ICustomFormmater
, so it only returns an instance of a DateTimeFormatInfo
or CultureInfo
if no provider is found. It seems that the DateTime.ToString
method does not honor the ICustomFormatter
interface like the StringBuilder.Format
method does, as your String.Format
example shows.
我同意则DateTime.ToString
方法应该支持 ICustomFormatter
界面,但似乎目前并不。这可能都已经改变或将改变.NET 4.0。
I agree that the DateTime.ToString
method should support the ICustomFormatter
interface, but it does not seem to currently. This may all have changed or will change in .NET 4.0.
这篇关于如何创建和使用自定义的IFormatProvider的日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!