gpt4 book ai didi

asp.net - 有没有办法为 ASP.NET 中的应用程序定义时区?

转载 作者:行者123 更新时间:2023-12-01 00:08:35 25 4
gpt4 key购买 nike

有没有办法在 ASP.NET 中为应用程序定义时区,以便从当前服务器时间读取/与当前服务器时间进行比较的所有时间都被隐式转换,或者我是否需要在每个 DateTime.Now 调用时放入转换语句?

最佳答案

我不确定 ASP 的最新发展,但这个 article from 2006提供了一个有趣的答案:

The problem is that timezone information is not directly available through the web browser. You could use heuristics to determine the correct time zone or you will have to store the timezone settings for a user based on their selection.



.Net 3.5 及其 TimeZoneInfo..ConvertTime 可能不需要以下内容方法,但为了完整起见:

Once you have the timezone settings you now need to translate the times. You should always store your date/time values in the DB in UTC. This eliminates many conversion issues. If you store the information in UTC then you need only translate from UTC to the user's local timezone when you display the data to them and you need to convert from their time zone to UTC when you get date/time values from them.

What makes this more difficult is the fact that the TimeZone class is not all that useful. Fortunately in v2.0 DateTime was updated to support an indicator on whether the time is in UTC or not. You can convert a DateTime to UTC using the DateTime.ToUniversalTime method. Unfortunately however you can't convert it back.

The ToLocalTime method uses the local time zone which, when run on the server, uses the server's time zone which isn't what you wanted. Even worse however is that you can't simply create a TimeZone object and use it as that support doesn't exist.

Michael Brumm created a nice little class for being able to create and use time zones easily. I personally use a heavily modified version of that code in my own apps and it works nicely. Here are the steps to convert from a DB UTC value to the local user's time zone.



1) 获取用户存储的时区值
2) 创建一个 SimpleTimeZone 类来包装它(使用一些映射方案将 DB 值映射到底层 Windows 注册表版本)
3) 使用 SimpleTimeZone.ToLocalTime 方法将 DateTime 值转换为本地时间。

For performance reasons you should probably get and initialize the SimpleTimeZone instance and cache it in the Items property for the length of the request so you don't have to keep creating it.

For converting from the user's local timezone to UTC do the reverse:



1)从用户那里获取存储的时区值
2)创建一个 SimpleTimeZone 类来包装它
3) 使用 SimpleTimeZone.ToUniversalTime 方法将 DateTime 转换为 UTC。

关于asp.net - 有没有办法为 ASP.NET 中的应用程序定义时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/301168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com