为什么DateTime.ParseExact(String,String,IFormatProvider)需要IFormatProvider? [英] Why DateTime.ParseExact(String, String, IFormatProvider) need the IFormatProvider?
问题描述
如果我们使用 日期时间使用指定的格式解析 c> ParseExact 方法,为什么我们需要提供一个IFormatProvider对象吗?
If we're using the ParseExact
method for exact date-time's parsing using a specified format, why do we need to provide a IFormatProvider object? what is the point behind it?
例如:
DateTime.ParseExact(dateString, format, provider);
为什么在这里需要提供者
?
推荐答案
为什么我们需要提供一个IFormatProvider对象?它背后有什么意义?
why do we need to provide a IFormatProvider object? what is the point behind it?
它允许特定于文化的选项。特别是:
It allows for culture-specific options. In particular:
- 您使用的格式可以是标准的日期/时间格式,这意味着不同文化中的不同模式
- 您可以在模式中使用
:
或/
,这意味着文化特定的字符时间分隔符或日期分隔符分别 - 解析月份和日期名称时,这些清楚地依赖于文化
- 文化也决定了默认日历将影响结果
- The format you use could be a standard date/time format, which means different patterns in different cultures
- You could use
:
or/
in your pattern, which mean culture-specific characters for the time separator or date separator respectively - When parsing month and day names, those clearly depend on culture
- The culture determines the default calendar as well, which will affect the result
作为最后一点的一个例子,请考虑在美国文化中解释相同的确切字符串和格式或沙特阿拉伯:
As an example of the last point, consider the same exact string and format, interpreted in the culture of the US or Saudi Arabia:
using System;
using System.Globalization;
class Test
{
static void Main()
{
CultureInfo us = new CultureInfo("en-US");
CultureInfo sa = new CultureInfo("ar-SA");
string text = "1434-09-23T15:16";
string format = "yyyy'-'MM'-'dd'T'HH':'mm";
Console.WriteLine(DateTime.ParseExact(text, format, us));
Console.WriteLine(DateTime.ParseExact(text, format, sa));
}
}
当与美国文化解析时,公历是使用 - 而当与沙特阿拉伯文化解析时,使用Um Al Qura日历,其中1434是我们当前的年份(正如我写这个答案)。
When parsing with the US culture, the Gregorian calendar is used - whereas when parsing with the Saudi Arabian culture, the Um Al Qura calendar is used, where 1434 is the year we're currently in (as I write this answer).
这篇关于为什么DateTime.ParseExact(String,String,IFormatProvider)需要IFormatProvider?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!