I need to convert DateTime variables between random cultures which will be read from config files.
I have the following code which works but I don't know why, and I'm not sure I trust it across all cases because the DateTime.Parse has no parameter specifying what format the convertedDt variable is in.
void ATestConversion(DateTime testDate)
{
CultureInfo ci = CultureInfo.CreateSpecificCulture("de-DE"); // assume de-DE read from config
string convertedDt = testDate.ToString(ci);
// How does this work without knowing convertedDt culture?
DateTime myDate = DateTime.Parse(convertedDt, CultureInfo.CreateSpecificCulture("fr-FR")); // fr-FR read from config
}
However, whenever I try something like this code below that I would expect to work I get: string not recognized as a valid DateTime
myDate = DateTime.ParseExact(convertedDt, ci.DateTimeFormat.FullDateTimePattern, new CultureInfo("fr-FR"));
In this code I can provide the dynamic format that the inbound string is in, along with the CultureInfo of what it needs to be converted to.
I see many examples like this:
DateTime.ParseExact(myDate, "dd/MMM/yyyy HH:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
where the format is hardcoded. I am basically trying to do the same but with dynamic formats. Why does my code not work when specifying the FullDateTimePattern of culture A and the actual CultureInfo of culture B?
How can I guarantee the conversions are correct between two run-time specified cultures?