title: How to create and use a custom IFormatProvider for DateTime?
body: <p>I was trying to create an <code>IFormatProvider</code> implementation that would recognize custom format strings for DateTime objects. Here is my implementation:</p>
  
  <pre><code> 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();
     }
    } 
  </code></pre>
  
  <p>I was expecting to be able to use it in the <code>DateTime.ToString(string format, IFormatProvider provider)</code> method like so, but :</p>
  
  <pre><code>DateTime d = new DateTime(2000, 1, 2);
  string s = d.ToString("mycustomformat", new MyDateFormatProvider());
  </code></pre>
  
  <p>In that example, running in the US Culture, the result is <code>"00cu0Ao00or0aA"</code>, apparently because the standard DateTime format strings are being interpreted.</p>
  
  <p>However, when I use the same class in the following way:</p>
  
  <pre><code>DateTime d = new DateTime(2000, 1, 2);
  string s = String.Format(new MyDateFormatProvider(), "{0:mycustomformat}", d);
  </code></pre>
  
  <p>I get what I expect, namely <code>"Sun Jan 02"</code></p>
  
  <p>I don't understand the different results. Could someone explain?</p>
  
  <p>Thanks!</p>