Royi Namir
Royi Namir

Reputation: 148744

CultureInfo on DateTime.ParseExact?

I don't understand Why there is an overload with IFormatProvider in DateTime.ParseExact ?

If I'm defining exactly how it should be parsed ( spaces , separators etc) , then theres should be no problem :

All these 3 examples show the same result:

example 1

CultureInfo provider =CultureInfo.CreateSpecificCulture("en-US");
var t=  DateTime.ParseExact("13-2-2013", "d-M-yyyy", provider, DateTimeStyles.None);  
Console.WriteLine (t); //13/02/2013 00:00:00

example 2

  CultureInfo provider =CultureInfo.CreateSpecificCulture("en-US");
  var t=    DateTime.ParseExact("13/2/2013", "d/M/yyyy", provider, DateTimeStyles.None);  
  Console.WriteLine (t); //13/02/2013 00:00:00

example 3

 CultureInfo provider =CultureInfo.CreateSpecificCulture("en-US");
var t=  DateTime.ParseExact("13@@@2@@@2013", "d@@@M@@@yyyy", provider, DateTimeStyles.None);  
 Console.WriteLine (t); //13/02/2013 00:00:00

So why do i need to provide provider If I'm explicitly defining the structure ?

Upvotes: 11

Views: 10241

Answers (3)

tungi52
tungi52

Reputation: 642

I can mainly imagine a web application and maybe a form, where the client submits informations to the server. This form also contains a datepicker, and sends the selected date based on the specific culture. So if the website used in the USA, they send 13/2/2013, while from Germany you get 13.2.2013. So how you handle the date in your server side code?

You could use sometheing like this in ASP.NET MVC (thanks to Sergey, Get CultureInfo from current visitor and setting resources based on that?):

var userLanguages = Request.UserLanguages;
CultureInfo ci;
if (userLanguages.Count > 0)
{
    try
    {
        ci = new CultureInfo(userlanguages[0]);
    }
    catch(CultureNotFoundException)
    {
         ci = CultureInfo.InvariantCulture;
    }
}
else
{
    ci = CultureInfo.InvariantCulture;
}

And then parse to datetime:

var t = DateTime.ParseExact(formDateString, "d/M/yyyy", ci, DateTimeStyles.None);  

Upvotes: 1

Guffa
Guffa

Reputation: 700800

There are still format specifiers that are culture dependant, like the time separator (:) and the date separator (/). Those doesn't match a specific character, but the separator specified in the culture.

Upvotes: 9

Jon
Jon

Reputation: 437784

Because:

  1. The specified format can include localized names of weekdays and months.
  2. The characters : and / in the format string do not represent literal characters but rather the separator as specified by the format provider (see the bottom of the table here).

Upvotes: 1

Related Questions