How to use IFormatProvider in DateTime.ParseExact

c#, datetime, iformatprovider

Solution

The format parameter says what pattern to use - but it doesn't say anything about which calendar, month names, short date format etc to use. That's up to the `IFormatProvider`.

For example, suppose you wanted to parse a value with the pattern `"dd MMMM yyyy"` - which month names would you expect to work? If you're using a month name of "February" but you're running on a machine with a system culture of French, it would fail - you'd need to specify an English culture (or the invariant culture) to get it to work. Likewise, you could specify a pattern of `"d"` to mean the short date format - but which short date format?

Even the calendar you use is affected by the format provider: the value could be parsed into the same year, month and day values in two cultures - but the meaning of those values would be very different in a Hijri calendar from a Gregorian calendar, for example.

Problem

Why should we use `IFormatProvider` in `DateTime.ParseExact` if there is already a format parameter? ``` DateTime.ParseExact(inputString, format, cultureInfo); ```

Original source