In C#, how does one use the DateTime format strings to control what parts of a date are displayed and at the same time not override the CultureInfo?
System.Globalization.CultureInfo cultureInfoUS = new System.Globalization.CultureInfo("en-US", false);
System.Globalization.CultureInfo cultureInfoGerman = new System.Globalization.CultureInfo("de-DE", false);
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfoUS;
DateTime date = DateTime.Parse("03-13-2012 01:30:00 PM");
Console.WriteLine(date.ToString(cultureInfoGerman));
//produces 13.03.2012 13:30:00
Console.WriteLine(date.ToString("MM/dd/yyyy", cultureInfoGerman));
//produces 03.13.2012 but should be 13.03.2012
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfoGerman;
Console.WriteLine(date.ToShortTimeString());
//produces: 13:30
Console.WriteLine(date.ToString("h:mm tt", cultureInfoGerman));
//produces: 1:30 but should be 13:30
Console.WriteLine(date.ToString("h:mm tt", cultureInfoUS));
//produces: 1:30 PM
You can see the comments in the above code. The output is partially adjusted by the CultureInfo but not entirely.
Also, the ToShortDateString and ToShortTimeString methods do not take an IProvider and therefore must rely on the current thread’s culture info. This is illustrated with the first example above. Is the expectation that you should change the current culture, call ToShortDateString and then revert the thread back to the original culture?
I don’t understand the comments in your code – the custom date/time format specifiers you are using behave exactly as I would expect. Why would you expect “MM/dd/yyyy” to put the day first?
If you want a custom format that is based on the pattern used by a given culture, you can build it by looking at
DateTimeFormatInfo.ShortDatePattern,DateTimeFormatInfo.ShortTimePatternetc. For example, if you wanted a custom format with the day of week followed by a culture-specific short time, you could use:No, you should use a standard date/time format string if you want something other than the current culture: