Home > Mobile >  How can I make DateTime.ToString("d") use the right locale or culture?
How can I make DateTime.ToString("d") use the right locale or culture?

Time:10-12

I have temporarily set my browser language and locale to English - United Kingdom even though I am in the United States.

In my Blazor WebAssembly site, on a component, I have a property that returns a string: myDate.ToString("d") System.Globalization.CultureInfo.CurrentCulture.DisplayName; that renders on my page as 6/27/2020en (GB), where myDate is a DateTime set to June 27, 2020 at 00:00:00.000.

Isn't is supposed to show the date in UK format, namely 27/06/2020? I can only guess that DateTime.ToString uses a setting other than CultureInfo.CurrentCulture. What could it be?

UPDATE: An explicit call to myDate.ToString("d", System.Globalization.CultureInfo.GetCultureInfo("en-GB"));` still outputs the m/d/yyyy format (U.S. format). Why might that be?

CodePudding user response:

Sorry, I cannot add comments. Have you checked your web.config? If it's set to "auto" it will use the client's culture and you may see different outcomes.

CodePudding user response:

DateTime.ToString() without any IFormatProvider passed will use the CultureInfo.DateTimeFormat (which is from the CurrentCulture) by default to set the formatting of the DateTime.

The documentation highlights this:

ToString() Converts the value of the current DateTime object to its equivalent string representation using the formatting conventions of the current culture.

You've changed your browser language to en-GB but that does not change your current culture.

CultureInfo spans many things which are normally set at an OS level by the user like the writing system, the calendar used, the sort order of strings, and formatting for dates and numbers.

Override the culture info by passing in the Great Britain locale to DateTime.ToString as an IFormatProvider to see the date in GB date format:

string gbDateTime = myDate.ToString("d", CultureInfo.GetCultureInfo("en-GB"))

Or set the current culture to the GB culture before calling .ToString():

CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-GB");
string gbDateTime = myDate.ToString("d");

Unless you specify a current culture, the application will show the date in the user's preferred date format (defined by their current locale, set in their OS) by default.

You do not need to specify anything to make your application display the date in local format.

  • Related