views:

609

answers:

3

The method signature for Date.TryParse is:

Public Shared Function TryParseExact ( _
    s As String, _
    format As String, _
    provider As IFormatProvider, _
    style As DateTimeStyles, _
    <OutAttribute> ByRef result As DateTime _
) As Boolean

I understand what format does, but what is the provider parameter for? I understand that you pass in a CultureInfo instance, but am unsure as to what it's purpose is.

Can anyone please enlighten me?

+7  A: 

The provider specifies the culture-specific format information about the date.

For example, you could pass in any of these cultures:

new CultureInfo("en-US")  // USA
new CultureInfo("fr-FR")  // France
new CultureInfo("it-IT")  // Italy
new CultureInfo("de-DE")  // Germany

And you would get the date formatted according to those cultures, such as:

  • en-US: 6/1/2009 4:37:00 PM
  • fr-FR: 01/06/2009 16:37:00
  • it-IT: 01/06/2009 16.37.00
  • de-DE: 01.06.2009 16:37:00

Another example: using the "d" format, which represents the M/d/yyyy short date pattern when using en-US for CultureInfo, consider:

DateTime dateValue;
string[] sampleDates = new[] { "31/8/2009", "8/31/2009" };
foreach (string currentDate in sampleDates)
{
    bool result = DateTime.TryParseExact(currentDate, new[] {"d"}, 
        new CultureInfo("en-US"), 
        DateTimeStyles.None, 
        out dateValue);
    Console.WriteLine("{0}: {1}", currentDate, result ? "valid" : "invalid");
    if (result)
    {
     Console.WriteLine("Result: {0}", dateValue);
    }
    Console.WriteLine();
}

Output:

31/8/2009: invalid

8/31/2009: valid
Result: 8/31/2009 12:00:00 AM

31/8/2009 is invalid since it doesn't fit the en-US culture format of M/d/yyyy, whereas 8/31/2009 is valid since it does.

Ahmad Mageed
+1  A: 

An IFormatProvider is a class that has knowledge of how to format something. TryParseExact needs to ask it (and in this case specifically, a CultureInfo), to see if there are any special culture-specific symbols in the string, such as days of week, AM/PM, etc.

Additionally, if you just pass the format in as one of the standard c# date format specifiers, the format provider must be consulted as to what that exactly translates to for the given culture.

womp
I see. I was under the impression that the IFormatProvider parameter is something of a "fallback" format matcher in case the format string you pass in does not do the job.Say I try to do:TryParseExact("18/06/2009", "ddMMyyyy", New CultureInfo("en-AU", DateTimeStyles.None, stringToWriteTo)Then TryParseExact will return false and nothing will be written to stringToWriteTo?
Andrew
A: 

Dates differ around the world, both in their format and in the words used for months. The IFormatProviders know about this.

James L