gpt4 book ai didi

c# - Azure 中的时区偏移不正确

转载 作者:行者123 更新时间:2023-11-30 15:40:21 27 4
gpt4 key购买 nike

Update - the problem didn't lie within the extension method

As it turned out, there was no actual problem with my extension method. When I feed it with a DateTime straight from the webserver like so DateTime.UtcNow.ToUserLocalTime() I realized that the method was actually producing the correct result. The problem was instead that I accidentally called it twice on the DateTimes that were displayed incorrectly - first in the controller and then again in the view. A really stupid mistake, realized after beating my head against the wall for hours. From now on it is called from the controller only.

我在 Azure 中运行的 ASP.Net MVC3 应用程序中遇到时区转换问题。当我在本地运行该应用程序时,一切都工作正常,但是当我在 Azure 中运行完全相同的代码时,它最终会关闭 1 个小时。

我为 DateTime 创建了一个扩展方法,用于根据用户选择的时区转换 DateTime。所有日期时间均以 UTC 格式存储。

public static DateTime ToUserLocalTime(this DateTime date)
{
date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
if (!string.IsNullOrEmpty(SecurityContext.CurrentUser.TimeZone))
{
var timezone = SecurityContext.CurrentUser.TimeZone;
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timezone);
return TimeZoneInfo.ConvertTime(date, timeZoneInfo);
}

return date;
}

SecurityContext.CurrentUser.TimeZone 是时区的字符串表示形式,在我的例子中 W.欧洲标准时间

当我从本地 SQL 数据库获取 DateTime 2011-12-02 13:46:22 并通过我的 ToUserLocalTime 方法运行它时,将其转换为 W.在我的本地环境中,欧洲标准时间 我得到的 2011-12-02 14:46:22 这是正确的。但是,当我在 Azure 中运行完全相同的代码时,从 SQL-Azure 数据库中读取数据(其中包含完全相同的日期时间和所选时区),我得到 2011-12-02 15:46:22。这让我很困惑,为什么最后休息了一个小时?

我真的不知道如何调试它,因为我无法在本地重现它。有没有办法在 Azure 角色中对此进行调试,以便我可以看到代码中到底发生了什么?类似于 Visual Studio 中的调试器?

我尝试在发布应用程序时启用 IntelliTrace,但是当我这样做时,应用程序无法启动,并在连接到 Azure-SQL 数据库时提示连接错误。我没有 IntelliTrace 经验,生成的日志能否告诉我有关此处发生的情况的任何信息?在这种情况下,值得花时间让 InteliTrace 发挥作用吗?

任何关于这里可能出现问题或如何调试它的想法将不胜感激。

最佳答案

使用怎么样

return TimeZoneInfo.ConvertTimeFromUTCTime(date, timeZoneInfo);

而不是

return TimeZoneInfo.ConvertTime(date, timeZoneInfo);

引用:http://social.msdn.microsoft.com/Forums/en-AU/windowsazuredevelopment/thread/04be9d07-fcdb-4bf2-b380-57c062382409

然后,您可以删除行 date = DateTime.SpecifyKind(date, DateTimeKind.Utc);,假设您的日期始终具有 Unspecified 类型

或者可能是夏令时把事情搞砸了?请参阅http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/92696af4-5169-4015-90eb-79da3c5136c2/

要对此进行测试,请尝试转到更改时区的页面,方法是单击计算机时钟并“更改日期和时间设置”。然后取消选中/选中“自动调整夏令时时间”。

关于c# - Azure 中的时区偏移不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9364304/

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