Search code examples
c#formatglobalizationdatetimepicker

Exact date and time format of DateTimePicker


According to this article I know, that DateTimePicker control does not reflect CurrentUICulture
So, how can I get the real culture it's using? I need that to get the string value of DateTimePicker in multi-language application, but in exactly the same format as user sees on form (and no, I can't set "hardcode" custom formatting).

Example:
When I'm working on Windows with my native Polish settings, then for LongTime it's: HH:mm:ss and time in DateTimePicker is displayed like: 09:26:50

Now, when I want to select different language in my application and change culture settings to US in form's constructor:

...
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
System.Threading.Thread.CurrentThread.CurrentUICulture = ci;

InitializeComponent();
....

then

MessageBox.Show(System.Globalization.DateTimeFormatInfo.CurrentInfo.LongTimePattern);

shows, that new time format is: h:mm:ss tt, yet DateTimePicker still is displaying: 09:26:50

When I try to get the time string like:

dateTimePicker1.Value.ToLongTimeString()

or

dateTimePicker1.Value.ToString(System.Globalization.DateTimeFormatInfo.CurrentInfo.LongTimePattern)

then time is displayed like: 9:26:50 AM

So my question is - how can I either know, that DateTimePicker is still using system's CultureInfo("pl-PL") or that it's display format is: HH:mm:ss ?


Solution

  • DateTimePicker is a native Windows control. It uses the time format as configured in the Control Panel + Region and Language applet. Which looks like this on my machine (I live in the USA):

    enter image description here

    So one way you can find out what format it uses is by storing the Thread.CurrentCulture value before you change it.

    Do note that changing the culture of the UI thread is a pretty dangerous thing to do. The problem is that any other thread in your program, especially little thread-pool and I/O completion threads, still run with the machine's default culture, as configured in the Administrative tab in the above screenshot. That can cause subtle bugs that are hard to find. Like a SortedList created on the UI thread that suddenly isn't sorted anymore in the worker thread. .NET 4.5 will provide a fix for this problem with the added CultureInfo.DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture properties.

    Rest assured that few users of your program will actually wish to run it in a language that doesn't match their machine setting and mother tongue. Providing a language change option in your UI is a demo feature, it doesn't actually get used.