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

帅比萌擦擦* 提交于 2019-12-18 10:37:38

问题


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?

For example:

DateTime.ParseExact(dateString, format, provider);

Why do we need the provider here?


回答1:


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

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



来源:https://stackoverflow.com/questions/18961520/why-datetime-parseexactstring-string-iformatprovider-need-the-iformatprovide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!