Date and Time format strings in .NET – IFormatProvider

Several of the overloads of ToString and the different Parse methods (Parse, ParseExact, TryParse and TryParseExact) defined on DateTime take an IFormatProvider parameter.

This interface defines a single method – GetFormat which takes a type and returns an object that provides formatting services for the specified type. When DateTime in concerned this object would be an instance of the DateTimeFormatInfo class.

The CultureInfo class also implements the IFormatProvider interface and will also return a DateTimeFormatInfo instance when called in the context of DateTime formatting. This is important, as CultureInfo is the most common implementer of IFormatProvider that is used for formatting DateTime instances for display.

It is unlikely that you will ever need to implement IFormatProvider yourself, at least when DateTime formatting is concerned.

The most common usages of IFormatProvider with DateTime are to provide a culture sensitive display of the DateTime instance and to parse a string representing a DateTime into a DateTime instance. This will be the subject of the next post.

Leave a Reply

Your email address will not be published. Required fields are marked *