DateTime.ToString and IFormatProvider

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.

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值