How to create and use a custom IFormatProvider for DateTime?

后端 未结 3 1517
陌清茗
陌清茗 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 18:53

    Use extension method :)

    public static class FormatProviderExtension
        {
            public static string FormatIt(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("ffffd dd MMM");
                            default:
                                return date.ToString("ffffd MMM dd");
                        }
                    default:
                        throw new FormatException();
                }
            }
    
            public static string ToString(this DateTime d, IFormatProvider formatProvider, string format)
            {
                return FormatIt(format, d, formatProvider);
            }
        }
    

提交回复
热议问题