Question

I'm trying to parse this datetime on an usa server, but it doesn't work:

string foo = "13 Lug 2013 14:15";
DateTime arrivalDateConfirmed = DateTime.ParseExact(foo, "dd MMM yyyy HH:mm", new CultureInfo("it-IT"));

On my Italian test machine work.

Was it helpful?

Solution

Try escaping the semicolon:

DateTime arrivalDateConfirmed = DateTime.ParseExact(foo, "dd MMM yyyy HH\\:mm", new CultureInfo("it-IT"));

You can find further info here: http://madskristensen.net/post/Quirk-in-the-DateTime-class.aspx.

The explanation is that the ":" character is considered a custom format specifier rather than a literal character, in this case the time separator. The parser will try to convert this separator to the specified culture. In this case the time separator for it-IT is the "." character. You should escape custom format specifier characters if you do not want them converted to the locale equivalent, as explained here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#escape

OTHER TIPS

You need to set the culture of the current thread to Italian, so it knows to parse Italian dates and not US dates, which it is currently set to. You also don't need to use ParseExact, just use Parse(). Make sure to set it back when you're done with your culturally sensitive code.

string foo = "13 Lug 2013 14:15";
Thread.CurrentThread.CurrentCulture = new CultureInfo("it-IT");
DateTime.Parse(foo);
Console.WriteLine(foo);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top