DateTime.ToString and IFormatProvider

来源:互联网 发布:如何查短信端口归属 编辑:程序博客网 时间:2024/05/29 07:39

DateTime.ToString and IFormatProvider

The DateTime.ToString method has four overloads, which ultimately all boil down to a single signature:

public string ToString(string format, IFormatProvider provider);

This method simply returns the following value:

DateTimeFormat.Format(
this, format, DateTimeFormatInfo.GetInstance(provider));

If the provider parameter is null, DateTimeFormatInfo.GetInstance uses CultureInfo.CurrentCulture.

The IFormatProvider interface has a single method:

public interface IFormatProvider
{
object GetFormat(Type formatType);
}

There are just three classes in the .NET Framework that support the IFormatProvider interface:

CultureInfo

DateTimeFormatInfo

NumberFormatInfo

The GetFormat method accepts a Type and returns an object of that Type. So if the CultureInfo.GetFormat method is called with the DateTimeFormatInfo Type, then it returns the value of its CultureInfo.DateTimeFormat property. As the name implies, the IFormatProvider implementation provides formatting information. In this example, a German CultureInfo object provides the IFormatProvider interface:

DateTime firstJan2000 = new DateTime(2000, 1, 1);
CultureInfo cultureInfo = new CultureInfo("de-DE");
listBox1.Items.Add(firstJan2000.ToString("D", cultureInfo));

The following string is added to the list box:

Samstag, 1. Januar 2000

The CultureInfo object provides the DateTimeFormatInfo, which includes the date-/time-formatting patterns and also the Calendar required to represent the date. The FxCop "Specify IFormatProvider" rule (see Chapter 13) enforces that the IFormatProvider parameter is always passed to DateTime.ToString. The idea behind this rule is to ensure that there is no ambiguity in the way the date is represented and that the developer has been forced to consider the globalization issues of the code.