Problem with DateTime.Now on Server
I have a great problem and I don't know how to solve it
I have created a web appli开发者_开发知识库cation and host it in USA server , and the users who access this web application from Egypt
The problem that i'm using DateTime.Now method inside the application and this method return the time of USA server not the time of the machine that use it in Egypt
How can i solve this problem ? please help me as soon as you can
Thanks in Advance
Well, you could start off by using DateTime.UtcNow
, transferring that to the client, and then performing the relevant time zone conversions at the client. That's usually a reasonable way of working - so long as you can do the processing at the client (e.g. in JavaScript).
Alternatively, ask the user their time zone so you can serve pages which use the local time, using TimeZoneInfo
. Of course if you know all your users are in Egypt you could potentially just hard-code that.
You need to convert the datetime value to the time zone of your users. One simple way to do this would be to call ConvertTime
and pass in the desired time zone as follows:
DateTime now = TimeZoneInfo.ConvertTime(DateTime.UtcNow,
TimeZoneInfo.FindSystemTimeZoneById("Egypt Standard Time"));
Generate the time using UTS, so that it is normed, and then display based on the location of the user or on their preferences.
You may want to read this also: Creating a DateTime in a specific Time Zone in c# fx 3.5
Well, you could use DateTime.UTCNow and then convert to local time.
精彩评论