CultureInfo on DateTime.ParseExact?

I don’t understand. Why is overloading using IFormatProvider in DateTime.ParseExact ?

If I determine exactly how it should be parsed (spaces, delimiters, etc.), then the problem will not be a problem:

All these 3 examples show the same result:

example 1

 CultureInfo provider =CultureInfo.CreateSpecificCulture("en-US"); var t= DateTime.ParseExact("13-2-2013", "dM-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 a provider if I explicitly define the structure?

+8
c # datetime
source share
3 answers

There are also format specifiers that are culture dependent, such as a time separator (:) and a date separator (/). They do not match a specific character, but the separator is specified in the culture.

+8
source share

Because:

  • The specified format may include localized weekday and month names.
  • Characters : and / in the format string do not represent alphabetic characters, but rather a delimiter specified by the format provider (see the bottom of the table here ).
+1
source share

Basically, I can present a web application and possibly a form where a client sends information to a server. This form also contains a datupik and sends the selected date based on a specific culture. Therefore, if the site is used in the USA, they send on 02/13/2013, and from Germany you receive 13.2.2013. So how do you handle the date in your server code?

You can use something similar in ASP.NET MVC (thanks to Sergey, Get CultureInfo from the current visitor and install resources based on this? ):

 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 analyze the date and time:

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

All Articles