In ASP.NET, how should I convert to and from GMT?
In Code-behind:
I store my Dates in SQL Server withDateTime.ToUniversalTime()
.
I then read the Date, and convert back with DateTime.ToLocalTime()
before presenting it on the Web page.
When my Web server is in an entirely different time zone from the client this doesn't work. All my conversions are taking place on the Web server. Having tried this in the code-behind, I believe I need to do it in the client.
What is the preferred method for making sure that the actual local time of the browser ge开发者_开发问答ts correctly converted to and from GMT?
One option is to ask the user about their timezone in their general profile information, then use that on the server.
If you can't just display the time with your server time zone identified (Such as saying "12:00pm Central time") or have the user provide their timezone in their profile, then you will need to use javascript to convert the time. I don't want to go through all of the steps, but this page has a good walkthrough of doing this:
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6016329.html
Note that the preferred method of showing users' local time would be to have them provide their timezone in their profile so you can do this conversion on the server.
Most implementations I've seen where local time is needed rely on the user specifying their timezone, this is then stored in their profile on the server and then used to adjust the presented date/times. This would seem to be the most robust method. An alternative would be to try to establish the users location using their IP address (GeoIP or similar) and adjust accordingly. This isn't wholly reliable as some companies have gateways that aren't geo-located with the user.
Most blogs on google point out to the fact that .NET does not provide a way to get the client's time zone.
However most say that either:
Ask the user to enter his timezone and then use that information to display the data
Use javascript function which returns browser’s time zone offset in minutes and then send it across to the server for further processing. Refer: http://weblogs.asp.net/cprieto/archive/2010/01/03/handling-timezone-information-in-asp-net.aspx
精彩评论