The IFormatProvider interface IFormatProvider usually implemented for you by the CultureInfo class, for example:
CultureInfo.CurrentCultureCultureInfo.CurrentUICultureCultureInfo.InvariantCultureCultureInfo.CreateSpecificCulture("de-CA") //German (Canada)
The interface is the gateway to a function that allows you to retrieve a set of culture-related data from a culture. The two public cultural objects that IFormatProvider can request are:
DateTimeFormatInfoNumberFormatInfo
As this usually works, you request an IFormatProvider to give you a DateTimeFormatInfo object:
DateTimeFormatInfo format; format = (DateTimeFormatInfo)provider.GetFormat(typeof(DateTimeFormatInfo)); if (format != null) DoStuffWithDatesOrTimes(format);
Itโs also known IFormatProvider that any IFormatProvider interface is probably implemented by a class that descends from CultureInfo or descends from DateTimeFormatInfo , so you can directly use the interface:
CultureInfo info = provider as CultureInfo; if (info != null) format = info.DateTimeInfo; else { DateTimeFormatInfo dtfi = provider as DateTimeFormatInfo; if (dtfi != null) format = dtfi; else format = (DateTimeFormatInfo)provider.GetFormat(typeof(DateTimeFormatInfo)); } if (format != null) DoStuffWithDatesOrTimes(format);
But don't do it
All this hard work has already been written for you:
To get DateTimeFormatInfo from IFormatProvider :
DateTimeFormatInfo format = DateTimeFormatInfo.GetInstance(provider);
To get NumberFormatInfo from IFormatProvider :
NumberFormatInfo format = NumberFormatInfo.GetInstance(provider);
The value of IFormatProvider is that you create your own cultural objects. As long as they implement IFormatProvider and return the objects they are asked for, you can bypass built-in cultures.
You can also use IFormatProvider for a method of transferring arbitrary cultural objects - through IFormatProvider . For example. name of god in different cultures
- the God
- the God
- Jehova
- Yahweh
- ืืืื
- ืืืื ืืฉืจ ืืืื
This allows your custom LordsNameFormatInfo class LordsNameFormatInfo navigate inside the IFormatProvider , and you can save idioms.
In fact, you will never need to call GetFormat method yourself.
Whenever you need an IFormatProvider , you can pass a CultureInfo object:
DateTime.Now.ToString(CultureInfo.CurrentCulture); endTime.ToString(CultureInfo.InvariantCulture); transactionID.toString(CultureInfo.CreateSpecificCulture("qps-ploc"));
Note Any code issued in a public domain. No attribution required.