How to localize DatePicker date format based on language defined in regional settings

I have English Windows 7 installed on my computer, and the default language is English (using "Regional and Language Settings"). When I read DateTimeFormat.ShortDatePattern using the following C # statement:

 System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.ShortDatePattern 

I got this result

 "M/d/yyyy" 

I also tried this statement and still got the same line.

 System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern "M/d/yyyy" 

However, now I changed the language to Regional and Language Settings and selected Danish. Now, if I go to the “Format” tab and in a short date format, you will see "M/d/åååå" , which is localized in Danish. This means that by changing the language, the date format is changed.

However, in my application, I still get the above English format string, even if the loaded CurrentUICulture is correct for da-DK for the Danish language. I want to display a localized ShortDateFormat, as shown in the regional settings. Do I need to do localization on my own or is there any way to do this. Please let me know if I missed something.

Edit: This information is added to further clarify the issue based on a discussion with Peter.

The combobox format speaks of Danish (Denmark). The format reads fine, Danish, but the line still says M / d / yyyy instead of M / d / åååå. This is the exact M / d / åååå line that I want to display in the DatePicker control. In other words, the watermark should display the localized ShortDatePattern. Still struggling ...

+4
source share
2 answers

Try setting CurrentCulture, not CurrentUICulture. For instance:

 Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK"); 

CurrentUICulture defines the resources required for the application.

CultureInfo specifies the default format for dates, times, numbers, currencies, text sort order, casing conventions and string comparisons, and what you need.

0
source

Here is a C # example that you can do. (Dump is a linqpad extension method that you can ignore in your own code).

A complete list of date format strings is available here.

 var languages = new List<string>{"de-DE", "en", "es-ES", "es-MX", "fr-FR", "it-IT", "pt-BR", "sv-SE"}; var date = DateTime.Now; languages.Select (l => new { Lang=l, d_shortDate = date.ToString("d", new CultureInfo(l)), D_longDate = date.ToString("D", new CultureInfo(l)), g_generalDate1 = date.ToString("g", new CultureInfo(l)), m = date.ToString("m", new CultureInfo(l)), y = date.ToString("y", new CultureInfo(l)), dd = date.ToString("dd", new CultureInfo(l)), mm = date.ToString("mm", new CultureInfo(l)), yy = date.ToString("yy", new CultureInfo(l)), }) .Dump(); 

Date formats

0
source

Source: https://habr.com/ru/post/1441795/


All Articles