Override default date separator in .net

I have a web server located in Switzerland and it is designed to serve both in the American region and in the European region. When a date is displayed in the Americas, the date is divided by period, not by slash.

In some cases, I want the user to be a period, if he is European, in others I want to use a slash. If I specify a format string to use a slash, it will be converted to a period based on computer settings. What do I need to do to specify the regional settings for each user (the user must log in, and I know which region he comes from).

+3
source share
4 answers

Globalization in ASP.NET should do everything for you to a large extent. See this MSDN article entitled How to Customize UI Culture and Culture for Globalizing ASP.NET Web Pages . This should be exactly what you want, because you just need to set the current (UI) culture for the current stream when the user logs in. Then you can call date.ToString()and return the text view in the correct format.

Equivalently, you could do something like this:

var culture = System.Globalization.CultureInfo.GetCultureInfo("en-GB");
var dateString = date.ToString(culture.DateTimeFormat);

But it really just does the same thing manually, and much less elegantly. You can also use the ASP.NET globalization infrastructure.

+5
source

, ,

#

date.ToString(@"dd\/MM\/yyyy");

. .

date.ToString("dd\/MM\/yyyy")
+3

DateTime.ToString(), :

 DateTime.Now.ToString("MM/dd/yyyy");

/ " ". , DateTime.Now.ToShortDateString(), .

System.Globalization.

: "" - -, , . IFormatProvider, , . :

DateTime.Now.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US"));
+2

, DateTime , :

DateTime dt = DateTime.Now;
dt.ToString(System.Globalization.CultureInfo.GetCultureInfo("fr-CH"));

See this on MSDN . Just write down your custom culture ("fr-CH", "en-US", etc.), then you can do more than just the USA against Switzerland.

Alternatively, I believe that you can create your own culture information to format dates correctly, but I never did.

+1
source

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


All Articles