How to create and use a custom IFormatProvider for DateTime?

后端 未结 3 1525
陌清茗
陌清茗 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

    The short explanation is that while

    DateTime.ToString(string format, IFormatProvider provider)
    

    lets you pass anything implementing IFormatProvider as one of its parameters, it actually only supports 2 possible types implementing IFormatProvider inside its code:

    DateTimeFormatInfo or CultureInfo

    If your parameter cannot be casted (using as) as either or those, the method will default to CurrentCulture.

    String.Format is not limited by such bounds.

提交回复
热议问题