How to create and use a custom IFormatProvider for DateTime?

后端 未结 3 1526
陌清茗
陌清茗 2020-12-05 18:35

I was trying to create an IFormatProvider implementation that would recognize custom format strings for DateTime objects. Here is my implementation:

<         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 19:16

    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.

    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.

提交回复
热议问题