Reputation: 148744
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
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
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