1

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?

Sanjay
  • 23
  • 1
  • 10
  • 1
    You can use dt.ToString("dd/MM/yyyy"); This converts the date object (dt) to dd/MM/yyyy format. – Souvik Ghosh Nov 28 '16 at 10:29
  • @SouvikGhosh , I dont want specific format. It must be according to local system datetime format and change when the local format is changed – Sanjay Nov 28 '16 at 10:31

2 Answers2

0

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.

Community
  • 1
  • 1
Joey
  • 344,408
  • 85
  • 689
  • 683
0

Here's my StackOverflow answer to a different thread, which should be what you're looking for.

How to get current user timezone in c#

The key is to always store DateTimes in the "UTC timezone" on your server (ie always use GetUTCDate() rather than GetDate() on a SQL Server machine), then get your client to pass which timezone they are in.

Then, you just need a bit of code which combines the two.

(Apologies for not cut'n'pasting the code from my other article response, but it's already nicely described there.)

Community
  • 1
  • 1
Mike Gledhill
  • 27,846
  • 7
  • 149
  • 159