C# 为什么 DateTime.ParseExact(String, String, IFormatProvider) 需要 IFormatProvider?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18961520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:42:21  来源:igfitidea点击:

Why DateTime.ParseExact(String, String, IFormatProvider) need the IFormatProvider?

c#datetimeiformatprovider

提问by Yair Nevet

If we're using the ParseExactmethod for exactdate-time's parsing using a specified format, why do we need to provide a IFormatProvider object? what is the point behind it?

如果我们使用ParseExact的方法确切的日期-时间的使用指定的格式解析,为什么我们需要提供的IFormatProvider对象?这背后的意义是什么?

For example:

例如:

DateTime.ParseExact(dateString, format, provider);

Why do we need the providerhere?

为什么我们需要provider这里?

采纳答案by Jon Skeet

why do we need to provide a IFormatProvider object? what is the point behind it?

为什么我们需要提供一个 IFormatProvider 对象?这背后的意义是什么?

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));
    }
} 

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).

解析美国文化时,使用公历 - 而解析沙特阿拉伯文化时,使用 Um Al Qura 日历,其中 1434 是我们目前所处的年份(在我写这个答案时)。