Sanjay Sanjay - 2 months ago 26
C# Question

c# : local system datetime format in server

I am trying to display the date on server in local system datetime format but it's taking the server datetime format. It's working fine when run in localhost but when ran in server, the format is MM/dd/yyyy (US format) irrespective of system datetime format. I have already tried these but no desired results

string DateTimeFormat = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern

System.Threading.Thread threadForCulture = new System.Threading.Thread(delegate() { });
string DateTimeFormat = threadForCulture.CurrentCulture.DateTimeFormat.ShortDatePattern;

Is there any other method to achieve this?


Well, you're using CurrentCulture and the code runs on the server, so what did you expect. Servers don't magically change their environment settings for every request.

If you want to conform to the preferred language of the user viewing the site, the best bet you have is the Accept-Language header. This answer details how to convert this to a CultureInfo in ASP.NET MVC. Mind you, this is still a somewhat limited approach, since you're limited to what the server supports and what the browser sends. The server has no other way than request header information to determine the user's preferences and the request header cannot really encode that I prefer de-de with ISO-8601 date format.

The easiest way then would be to pick a sensible default based on the request headers and offer an option to change it. Even on the client's machine with JavaScript you cannot get at most of that information. A web page simply has limits in how far it adheres to OS user preferences. So an easy way to opt out would be to add a setting so everyone can change it.